请我是新手。我搜寻了一下,看到的东西让我感到困惑。
如何减少数组中的重复项并将重复键的值添加到唯一的键中,如下所示。
我想要像arrayA
let arrayA = [
{ name: "temperature", data: {"2000-09-26": 82} },
{ name: "temperature", data: {"1997-03-08": 71} },
{ name: "current", data: {"1993-08-11": 79} },
{ name: "frequency", data: {"2004-01-17": 16} },
{ name: "current", data: {"1997-02-14": 65} }
]
let arrayB = [
{ name: "temperature", data: {"2000-09-26": 82, "1997-03-08": 71} },
{ name: "current", data: {"1993-08-11": 79, "1997-02-14": 65} },
{ name: "frequency", data: {"2004-01-17": 16} }
]
答案 0 :(得分:2)
您可以使用array#reduce
和Object.values()
。创建name
的哈希,并为给定的data
添加name
值。然后使用Object.values()
从对象获取值。
let arrayA = [ { name: "temperature", data: {"2000-09-26": 82} }, { name: "temperature", data: {"1997-03-08": 71} }, { name: "current", data: {"1993-08-11": 79} }, { name: "frequency", data: {"2004-01-17": 16} }, { name: "current", data: {"1997-02-14":
65} } ],
result = Object.values(arrayA.reduce((r,{name, data}) => {
r[name] = r[name] || {name, data: {}};
Object.assign(r[name].data, data);
return r;
},{}));
console.log(result);
答案 1 :(得分:0)
您在这里
let arrayB = arrayA.reduce((acc, curr) => {
const found = acc.find(i => i.name === curr.name)
if (found) {
// If this object is already there, merge their `data` property
Object.assign(found.data, curr.data)
} else {
// Otherwise add to the accumulator (`acc`)
acc.push(curr)
}
return acc
}, [])
关于reduce函数的参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
答案 2 :(得分:0)
var arrayA = [ { name: "temperature", data: {"2000-09-26": 82} }, { name: "temperature", data: {"1997-03-08": 71} }, { name: "current", data: {"1993-08-11": 79} }, { name: "frequency", data: {"2004-01-17": 16} }, { name: "current", data: {"1997-02-14": 65} } ]
var arrayB=_.map(_.groupBy(arrayA, 'name'),function(list){
return _.reduce(list,function(nObj,obj){
if(nObj.data && _.difference(_.keys(nObj.data),_.keys(obj.data))){
nObj.data=_.assign(nObj.data,obj.data)
}else{
nObj=obj
}
return nObj
},{})
})
console.log(arrayB)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.5.1/lodash.js"></script>