用对象属性替换数组元素

时间:2016-04-17 15:38:41

标签: javascript

我的对象

var person = [{ FIrstName: "", LastName: "", MiddleName: "" }];

我的数据

var names = [
    "Steve", "Mark", "John",     // person 1
    "James", "Andrew", "wells",  // person 2
    "Clarke", "Finche", "Gomes"  // person 3
];

所以我想将名字数组推送到人物对象中。

$(names).each(function (index, item) {
    //Here I need to push the values
}); 

如您所见,我没有姓氏和中间名的单独数组。

我希望输出为:

[
    { "FIrstName": "Steve", "LastName": "Mark", "MiddleName": "John" },
    { "FIrstName": "James", "LastName": "Andrew", "MiddleName": "wells" },
    { "FIrstName": "Clarke", "LastName": "Finche", "MiddleName": "Gomes" }
]

请帮助我。

4 个答案:

答案 0 :(得分:1)

这是你想要达到的目标。



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));
&#13;
&#13;
&#13;

此外,您可以先将数组拆分为数组...

&#13;
&#13;
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));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用for循环,增加i乘以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]
    });
}

答案 2 :(得分:0)

可能偏离主题,但如果您考虑使用Lodash

_.map(_.chunk(names, 3), function (person) {
    return _.zipObject(['FirstName', 'LastName', 'MiddleName'], person);
});

DEMO

答案 3 :(得分:0)

这是Array#reduce()的小提案。

&#13;
&#13;
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>');
&#13;
&#13;
&#13;