这是我的数组
{ Colors: 'Blues',
Department: 'Clearance',
Size: [ 'Runners', 'Custom Sizes' ],
Shape: 'Round',
Designer: 'B. Smit',
}
我想要输出:
{ Colors: 'Blues',
Department: 'Clearance',
Size: 'Runners',
Shape: 'Round',
Designer: 'B. Smit',
}
{ Colors: 'Blues',
Department: 'Clearance',
Size: 'Custom Sizes',
Shape: 'Round',
Designer: 'B. Smit',
}
我尝试了这个但没有得到结果
答案 0 :(得分:1)
你可以做这样的事情
function convert(inp){
var result = [];
for(var i = 0; i< inp.Size.length; i++){
result.push({
Colors: inp.Colors,
Department: inp.Department,
Size: inp.Size[i],
Shape: inp.Shape,
Designer: inp.Designer
});
}
return result;
}
convert({
Colors: 'Blues',
Department: 'Clearance',
Size: [ 'Runners', 'Custom Sizes' ],
Shape: 'Round',
Designer: 'B. Smit',
});
答案 1 :(得分:1)
如果您使用的是ES6或现代浏览器......
const input = {
Colors: 'Blues',
Department: 'Clearance',
Size: [ 'Runners', 'Custom Sizes' ],
Shape: 'Round',
Designer: 'B. Smit'
};
const output = input.Size.map(size => (
Object.assign(
{},
input,
{
Size: size
}
)
));
alert(JSON.stringify(output, null, '\t'));
&#13;
答案 2 :(得分:0)
@sunnyn,尝试以下解决方案。确定它会对你有所帮助。
var obj = { Colors: 'Blues',
Department: 'Clearance',
Size: [ 'Runners', 'Custom Sizes' ],
Shape: 'Round',
Designer: 'B. Smit',
};
var tmpArr = [];
for(var index in obj.Size) {
var myCustObj = {};
for (var k in obj){
if (obj.hasOwnProperty(k)) {
myCustObj[k] = obj[k];
}
}
myCustObj.Size = obj.Size[index];
tmpArr.push(myCustObj);
}
console.log(tmpArr);