我的对象就是这样。
var myData = [
{ 123: 1},
{ 123: 2},
{ 124: 3},
{ 124: 4}
];
,预期结果是:
var myDataNew = [
{123: [1, 2]},
{124: [3,4]}
];
如何使用javascript实现此目标?
答案 0 :(得分:1)
您可以使用当前结构尝试此操作,其中myData数组中的每个对象只有一个成员。
const myData = [
{ 123: 1},
{ 123: 2},
{ 124: 3},
{ 124: 4}
];
const groupDuplicates = (arr) =>
arr.reduce((acc, val) => {
const key = Object.keys(val).toString();
const item = acc.find((item) => Object.keys(item).toString() === key);
if (!item) acc.push({ [key]: [val[key]]});
else item[key].push(val[key]);
return acc;
}, []);
console.log(groupDuplicates(myData));
答案 1 :(得分:0)
您可以使用以下代码:
var myData = [
{ 123: 1},
{ 123: 2},
{ 124: 3},
{ 124: 4}
];
/*
var myDataNew = [
{123: [1, 2]},
{124: [3,4]}
];
*/
var keys = myData.map(current=>Object.keys(current)[0]);
//console.log(keys);//(4) ["123", "123", "124", "124"]
var result = [];
keys.forEach((current,index)=>{
//findIndex in result
let id = result.findIndex(c=>{
if(c[current])
return c;
});
// not find
if(id===-1){
let obj = {};
obj[current] = [myData[index][current]];
result.push(obj);
// find, let push
}else{
result[id][current].push(myData[index][current]);
}
});
console.log(result);
答案 2 :(得分:0)
首先使用reduce函数创建一个对象,然后在其上循环并在新数组中推送该值
var myData = [{
123: 1
},
{
123: 2
},
{
124: 3
},
{
124: 4
}
];
let k = myData.reduce(function(acc, curr) {
let getKey = Object.keys(curr)[0];// get the key
let getVal = Object.values(curr)[0] //get the value
//check if key like 123,124 exist in object
if (!acc.hasOwnProperty(getKey)) {
acc[getKey] = [getVal]
} else {
acc[getKey].push(getVal)
}
return acc;
}, {})
let newArray = [];
for (let keys in k) {
newArray.push({
[keys]: k[keys]
})
}
console.log(newArray)