这是一个非常简单的JSON结构,类似于我的数据类型。
我需要返回整个人员数组。我觉得有一种适当的方法可以执行此操作,而无需创建新列表和新信息数组,以及用新数组拼接出旧数组。我只是想将新对象添加或添加到旧数组。
**JSON People Data** = [
{name: "n1",
info: [ {address: "a1", phone: "p1"}, {address: "a2", phone: "p2"} ]
},
{name: "n2",
info: [ {address: "a1", phone: "p1"}, {address: "a2", phone: "p2"} ]
]
问题:
如何将(地址和电话)的Info对象添加到第二个info数组的第二人称数组并返回整个people数组?
理想结果:
**JSON People Data** = [
{name: "n1",
info: [ {address: "a1", phone: "p1"}, {address: "a2", phone: "p2"} ]
},
{name: "n2",
info: [ {address: "a1", phone: "p1"}, {address: "a2", phone: "p2"}, {address: "a3", phone: "p3"} ]
]
我第一次尝试:
**const newListConcat** = people[1].info.concat({address: "a3", phone: "p3"})
尝试后:
**const newListPush** = people[1].info.push({address: "a3", phone: "p3"})
但要返回:
// console.log - [ {address: "a1", phone: "p1"}, {address: "a1", phone: "p1"}, {address: "a1", phone: "p1"} ]
答案 0 :(得分:0)
我纠正了一些错别字,但这可以按需工作:
const people = [
{
name: "n1",
info: [ {address: "a1", phone: "p1"}, {address: "a2", phone: "p2"} ]
},
{
name: "n2",
info: [ {address: "a1", phone: "p1"}, {address: "a2", phone: "p2"} ]
}
];
people[1].info.push({address: "a3", phone: "p3"});
console.log(people);
**const newListPush** = people[1].info.push({address: "a3", phone: "p3"})
答案 1 :(得分:0)
我不确定您的期望。致电info.push()
const people = [
{
name: 'n1',
info: [
{ address: 'a1', phone: 'p1' },
{ address: 'a2', phone: 'p2' },
],
},
{
name: 'n2',
info: [
{ address: 'a1', phone: 'p1' },
{ address: 'a2', phone: 'p2' },
],
},
];
people[1].info.push({address: "a3", phone: "p3"});
console.log(JSON.stringify(people, null, 2));