我正在循环一些JSON,并试图在每次迭代时在现有的“master”对象中推送一个新对象。基本上,我正在寻找一种推送方法将对象推入对象而不是将它们推入数组中。
这只会推送本地对象中的一个对象。
var local = {};
for (let i = 0; i < data[2].length; i++) {
let friend = {};
friend.name = data[2].users[i][0].name;
friend.screenName = data[2].users[i][0].name;
friend.avatar = data[2].users[i][0].name;
local["friend"] = friend;
};
理想情况下,我希望最终的本地对象看起来像:
{ friend:
{ name: '123',
screenName: '123',
avatar: '123' },
{ name: '123',
screenName: '123',
avatar: '123' },
{ name: '123',
screenName: '123',
avatar: '123' },
{ name: '123',
screenName: '123',
avatar: '123' } }
答案 0 :(得分:3)
只需使用一系列朋友:
var local = {
friends:[]//an array of friends
};
for (let i = 0; i < data[2].length; i++) {
let friend = {};
friend.name = data[2].users[i][0].name;
friend.screenName = data[2].users[i][0].name;
friend.avatar = data[2].users[i][0].name;
local.friends.push(friend);
};
或者更容易使用地图:
var local={
friends:data[2].users.map(el=>({
name:el.name,
screenName:el.name,
avatar:el.name
}))
};
所以这个结构出现了结果:
{
friends: [
{ name: '123',
screenName: '123',
avatar: '123' },
{ name: '123',
screenName: '123',
avatar: '123' },
{ name: '123',
screenName: '123',
avatar: '123' },
{ name: '123',
screenName: '123',
avatar: '123' }
]
}