My object
var person = [{ FIrstName: "", LastName: "", MiddleName: "" }];
My data
var names = [
"Steve", "Mark", "John", // person 1
"James", "Andrew", "wells", // person 2
"Clarke", "Finche", "Gomes" // person 3
];
So I want to push the names array in person object.
$(names).each(function (index, item) {
//Here I need to push the values
});
As you can see I don't have separate arrays for last names and middle names.
I want my output as :
[
{ "FIrstName": "Steve", "LastName": "Mark", "MiddleName": "John" },
{ "FIrstName": "James", "LastName": "Andrew", "MiddleName": "wells" },
{ "FIrstName": "Clarke", "LastName": "Finche", "MiddleName": "Gomes" }
]
Please assist me.
Here is what you want to achieve.
var names = ["Steve","Mark","John","James","Andrew", "wells","Clarke","Finche","Gomes"];
var person = [];
for(var i=0; i<names.length; i+=3) {
person.push({
FIrstName: names[i],
LastName: names[i+1],
MiddleName: names[i+2]
});
}
document.write(JSON.stringify(person));
Also you can firstly split you array to array of chunks..
var names = ["Steve","Mark","John","James","Andrew", "wells","Clarke","Finche","Gomes"];
var chunks = [];
while(names.length) {
chunks.push(names.splice(0, 3));
}
var result = chunks.map(function(person) {
return {
FIrstName: person[0],
LastName: person[1],
MiddleName: person[2]
}
});
document.write(JSON.stringify(result));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With