我有一个包含许多几乎完全相同的对象的数组。我想将这些对象合并为一个,同时保持它们之间的数据不相同。
这是我的数据:
function updateBackgroundColour(selectElem) {
var i = selectElem.selectedIndex; // Get the selected option's index.
if (i < 0) {
return; // Nothing is selected.
}
// Set the background-color CSS attribute of the <body> element to
// the value attribute of the selected option in our <select> element.
document.body.style.backgroundColor = selectElem.options[i].value;
}
我希望最终结果是:
<form>
Background color:
<!-- Note the onchange attribute. "this" refers to the changing element. -->
<select id="background" onchange="updateBackgroundColour(this)">
<option value="red">Red</option>
<option value="MediumSpringGreen">Medium Spring Green</option>
<option value="#34495e">Wet asphalt</option>
</select>
<form>
任何帮助将不胜感激!
答案 0 :(得分:0)
var a1 = [
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 1, name: 'Cat 1'}
]
},
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 2, name: 'Cat 2'}
]
}
];
var a2 = [];
_.forEach(a1, function(item){
if(a2.length === 0){
a2.push(item);
}else{
_.forIn(item, function(value, key){
if(!a2[0].hasOwnProperty(key)){
a2[0][key] = value;
}else{
if(typeof value === "object" && value.length > 0){
_.forEach(value, function(v){
console.log("Pushing Item into Categories")
a2[0][key].push(v);
})
}
}
})
}
})
console.log(a2)
这不是最优雅的解决方案,但它可以完成工作,并将任何长度数组“a1”组合成长度为1个Object的数组,并将任何嵌套数组合并到它迭代的项目中。 / p>
因此,它也适用于以下数组......仅仅是为了示例:
var a1 = [
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 1, name: 'Cat 1'}
],
franks: [
{"blaH":"blah"}
]
},
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 2, name: 'Cat 2'}
] ,
franks: [
{"blaH":"blah1"}
]
} ,
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 2, name: 'Cat 2'}
] ,
franks: [
{"blaH":"blah2"},
{"blaH":"blah3"}
]
}
];