我想将对象列表附加为
listObj = {1:{id:1,name:"fgh"}, 2:{id:2, name:ghj}}
到数组
arrayObj = {child:[
0:{id:3,name:fghj}
1:{id:9, name:cvbn}
]}
所以最终期望的arrayObj应该是
arrayObj = {child:[
0:{id:3,name:fghj}
1:{id:9, name:cvbn}
2:{id:1,name:"fgh"}
3:{id:2, name:ghj}
]}
我试过追加但是没有给出预期的结果
答案 0 :(得分:1)
通过for in
循环获取与当前对象相关的每个属性,检查它们是否在当前对象中并将它们推入arrayObj.child
数组。
var listObj = { 1: {id:1, name:"fgh"}, 2: {id:2, name:"ghj"}}
var arrayObj = {child:[
{id:3,name:"fghj"},
{id:9, name:"cvbn"}
]};
for(var prop in listObj){
if(listObj.hasOwnProperty(prop)) {
arrayObj.child.push(listObj[prop]);
}
}
console.log(arrayObj.child);

或@Nina建议,通过Object.values()
。请注意,我们也使用... spread
运算符。
var listObj = { 1: {id:1, name:"fgh"}, 2: {id:2, name:"ghj"}}
var arrayObj = {child:[
{id:3,name:"fghj"},
{id:9, name:"cvbn"}
]};
arrayObj.child.push(...Object.values(listObj));
console.log(arrayObj.child);

答案 1 :(得分:1)
您可以使用源代码对象的Object.values
获取值,并使用spread syntax ...
将项目推送到目标数组。
var listObj = { 1: { id: 1, name: 'fgh' }, 2: { id: 2, name: 'ghj' } },
arrayObj = { child: [{ id: 3, name: 'fghj' }, { id: 9, name: 'cvbn' }] };
arrayObj.child.push(...Object.values(listObj));
console.log(arrayObj);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)
您可以使用
将其转换为数组Object.keys(listObj).map(function (key) { return listObj[key]; });
let listObj = {1:{id:1,name:"fgh"}, 2:{id:2, name:'ghj'}};
// converts listObj into an array
var arr = Object.keys(listObj).map(function (key) { return listObj[key]; });
//console.log(arr);
arrayObj = {child:[
{id:3,name:'fghj'},
{id:9, name:'cvbn'}
]}
//just concat into the array now
arrayObj.child = arrayObj.child.concat(arr);
console.log(arrayObj);