How to Push Specific Key and Value in Array?
We can add dynamically push specific key-value pairs in the jquery array. Create an array with key and value in jquery to push specific key I just completed this tutorial only for you to explain with an example.
Create automatically 0 1 2 3 4 5 … etc, but if you want to push both key and value then you can not specify key.
Example
<!DOCTYPE html>
<html>
<head>
<title>How to push specific key and value in array? - devnote.in</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<span id="displayData"></span>
<script type="text/javascript">
var dataArrays = [
{ "id" : "1", "first_nm" : "joi", "last_nm" : "die" },
{ "id" : "2", "first_nm" : "loi", "last_nm" : "jay" },
{ "id" : "3", "first_nm" : "savan", "last_nm" : "milap" },
{ "id" : "4", "first_nm" : "lorem", "last_nm" : "jay1" },
{ "id" : "5", "first_nm" : "lipsum", "last_nm" : "jay2" },
{ "id" : "6", "first_nm" : "content", "last_nm" : "jay3" },
];
var Objects = {};
$.each(dataArrays, function (i, value) {
Objects[value.id] = value.first_nm;
});
$('#displayData').text(JSON.stringify(Objects, null, 4));
</script>
</body>
</html>
Output
==== OR ====
Example
<!DOCTYPE html>
<html>
<head>
<title>How to Push Specific Key and Value in Array? - devnote.in</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<span id="displayData"></span>
<script type="text/javascript">
var dataArrays = [
{ "id" : "1", "first_nm" : "joi", "last_nm" : "die" },
{ "id" : "2", "first_nm" : "loi", "last_nm" : "jay" },
{ "id" : "3", "first_nm" : "savan", "last_nm" : "milap" }
];
var Objects = [];
$.each(dataArrays, function (i, value) {
Objects.push({first_nm: value.first_nm, last_nm: value.last_nm});
});
$('#displayData').text(JSON.stringify(Objects, null, 4));
</script>
</body>
</html>