这是我的json对象:
{
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
}
我希望我的预期输出如下:
[
{id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId:5},
{id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId:1}
]
答案 0 :(得分:4)
您选择.map
是正确的。问题是,您正在尝试更新对象,并使用引用传递对象。所以所有对象都将保持相同的id。您必须创建一个副本,以便不覆盖值。您可以使用Object.assign。
var data = {
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
};
var result = data.storeId.map(function(id){
return Object.assign({}, data, {storeId: id});
});
console.log(result)
如果您不习惯使用ES6功能,可以查看以下内容:How do I correctly clone a JavaScript object?
答案 1 :(得分:1)
您可以在数组.map()
上使用storeId
并返回一个新对象,其当前值为storeId
的值。
var obj = {
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
};
var data = obj.storeId.map(el => {
let newObject = Object.assign({}, obj);
newObject.storeId = el;
return newObject;
})
console.log(data);

答案 2 :(得分:1)
您可以使用带有扩展语法的array#map
来创建包含所有现有属性和个人storeId
的对象。
var obj = {id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId: [ 5, 1 ]}
result = obj.storeId.map(storeId => ({...obj, storeId}) )
console.log(result);
答案 3 :(得分:0)
var data = {
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
}
var finalData = data.storeId.map(x => {
return({
id: data.id,
cno: data.cno,
username: data.username,
name: data.name,
desc: data.desc,
storeId: x
})
});
console.log(finalData);
我试过这个我现在得到了正确答案,这是一个好方法吗?
答案 4 :(得分:-1)
var value = {
id: 3,
cno: 103,
username: 'basha',
name: 'New Complaint',
desc: 'Need bag',
storeId: [ 5, 1 ]
}
var result = value['storeId'].map(function(val){
var t = {}
for(key in value){
t[key] = value[key]
}
t['storeId'] = val
return t;
})
console.log(result)