gpt4 book ai didi

javascript - 用对象属性替换数组元素

转载 作者:行者123 更新时间:2023-11-29 15:28:58 24 4
gpt4 key购买 nike

我的对象

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

我的数据

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

所以我想将 names 数组推送到 person 对象中。

$(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" }
]

请帮助我。

最佳答案

这是您想要实现的目标。

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));

您也可以首先将数组拆分为 block 数组..

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));

关于javascript - 用对象属性替换数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36678572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com