Reputation: 9435
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.
Upvotes: 3
Views: 75
Reputation: 386570
This is a small proposal with Array#reduce()
.
var keys = ['FirstName', 'LastName', 'MiddleName'],
names = ["Steve", "Mark", "John", "James", "Andrew", "wells", "Clarke", "Finche", "Gomes"],
persons = names.reduce(function (r, a, i) {
var index = Math.floor(i / 3);
r[index] = r[index] || {};
r[index][keys[i % 3]] = a;
return r;
}, []);
document.write('<pre>' + JSON.stringify(persons, 0, 4) + '</pre>');
Upvotes: 0
Reputation: 21844
Could be off-topic, but if you consider using Lodash:
_.map(_.chunk(names, 3), function (person) {
return _.zipObject(['FirstName', 'LastName', 'MiddleName'], person);
});
Upvotes: 0
Reputation: 3911
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));
Upvotes: 1
Reputation: 8926
Use for
loop with increment i
by 3
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]
});
}
Upvotes: 0