我所拥有的:
myArray = [ {type: "My Application"}, {type: "My Component"}, {color: ["red"] } ]
我需要什么:
withUniqueKeys = [ {type: ["My Application", "My Component"] }, {color: ["red"]} ]
我将如何遍历myArray以获得像withUniquKeys这样的数组?我玩这个WAAAYYYY太久了。 Lodash的解决方案也可以。
答案 0 :(得分:4)
您可以使用reduce和Object.entries
let myArray = [ {type: "My Application"}, {type: "My Component"}, {color: "red" } ]
let op = myArray.reduce((op,inp)=>{
let [key,value] = Object.entries(inp)[0]
op[key] = op[key] || []
op[key].push(value)
return op
},{})
// in case you want property with one value to be object only
let final = Object.entries(op)
.map(([key,value]) => ( {[key]: value.length === 1 ? value[0] : value}))
console.log(final)
IMO最好使您的数据结构保持一致,这样便于以后使用,否则您需要检查值是字符串还是数组,而不是应用方法
let myArray = [ {type: "My Application"}, {type: "My Component"}, {color: "red" } ]
let op = myArray.reduce((op,inp)=>{
let [key,value] = Object.entries(inp)[0]
op[key] = op[key] || []
op[key].push(value)
return op
},{})
console.log(op)
答案 1 :(得分:1)
尝试一下:
let myArray = [ {type: "My Application"}, {type: "My Component"}, {color: ["red"] } ]
myArray = myArray.reduce((acc, el) => {
let prop = Object.keys(el)[0];
if (!acc[prop]) acc[prop] = [el[prop]];
else acc[prop].push(el[prop])
return acc;
},{})
myArray = Object.keys(myArray).map(d => ({[d]:myArray[d].length ===1?myArray[d][0]:myArray[d]}));
console.log(myArray)
答案 2 :(得分:1)
答案 3 :(得分:0)
首先,您可以使用Array.reduce()按ng serve
进行分组。然后,在第二步中,可以对生成的Array.map()使用Object.entries()以获得所需的结构:
keys
let myArray = [
{type: "My Application", category: "game"},
{type: "My Component", category: "other"},
{color: "red" }
];
let res = myArray.reduce((acc, curr) =>
{
Object.keys(curr).forEach(k =>
{
acc[k] = (acc[k] || []).concat(curr[k]);
});
return acc;
}, {});
res = Object.entries(res).map(([k, v]) => ({[k]: v.length > 1 ? v : v[0]}));
console.log(res);
请注意,如果您的输入对象中有一对以上的.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
,这种方法也将起作用。
答案 4 :(得分:0)