【问题标题】:Javascript merge multiple objects in an arrayJavascript合并数组中的多个对象
【发布时间】:2021-05-07 13:12:42
【问题描述】:

我试图通过键合并数组中的对象。我尝试了一些解决方案,但无法解决。我的数组就像;

[0:{PersonIds: "6",TypeIds: "2",VekilIds: "6"},1:{PersonIds: "4",TypeIds: "27",VekilIds: "11"}]

我想得到的是;

[0:{PersonIds: "6,4",TypeIds: "2,27",VekilIds: "6,11"}]

感谢您的帮助

【问题讨论】:

  • 您知道写入的数据类型不是有效的 JavaScript,对吧?
  • 这就像将两个字符串合并为一个,而不是合并两个对象
  • 那是来自远程的数据。我刚刚记录了它

标签: javascript jquery arrays


【解决方案1】:

这样的事情会起作用:

const myArr = [
  {PersonIds: "6",TypeIds: "2",VekilIds: "6"},
  {PersonIds: "4",TypeIds: "27",VekilIds: "11"},
];


const myObj = myArr.reduce((acc, cur, idx) => {
  const newAcc = {...acc};
  for (let [key, val] of Object.entries(cur)) {
    if (!newAcc[key]) {
      newAcc[key] = val;
    } else {
      newAcc[key] = `${newAcc[key]},${val}`;
    }
  }
  return newAcc;
});

console.log(myObj);

它使用Array.prototype.reduce 来遍历整个数组。 Because we omit an initial value, it skips the first index and just uses the first index as the initial value。然后对于数组中的每个后续对象,我们遍历其键并检查该键是否存在于累加器上——如果没有,我们将其插入值;如果是这样,我们从当前迭代中附加该键的值,用逗号分隔。

【讨论】:

  • 很高兴为您提供帮助——编码愉快!
【解决方案2】:

做同样事情的另一种方法,但将值放入数组而不是逗号分隔的字符串。

let result = [{}];
let array = [{PersonIds: "6",TypeIds: "2",VekilIds: "6"}, {PersonIds: "4",TypeIds: "27",VekilIds: "11"}];

for (let key in array) {
    for(let value in array[key]) {
        if (!result[0][value]) { result[0][value] = [] } 
        result[0][value].push(array[key][value]);
    }
}

console.log(result);

如果您不需要对象数组但可以使用对象,这里有一个选项,将值存储为每个对象属性中的值数组:

let result1 = {};
let array = [{PersonIds: "6",TypeIds: "2",VekilIds: "6"}, {PersonIds: "4",TypeIds: "27",VekilIds: "11"}];

for (let key in array) {
for(let value in array[key]) {
    if (!result1[value]) { result1[value] = [] } 
    result1[value].push(array[key][value]);
}
}
console.log(result1);

这是第二个选项,没有包含数组,对象属性根据您的原始请求格式化为字符串:

result2 = {};
let array = [{PersonIds: "6",TypeIds: "2",VekilIds: "6"}, {PersonIds: "4",TypeIds: "27",VekilIds: "11"}];


for (let key in array) {
for(let value in array[key]) { 
    if (!result2[value]) { result2[value] = array[key][value]; }
    else { result2[value] = result2[value].concat(",", array[key][value]) }
}
}
console.log(result2);

【讨论】:

    【解决方案3】:

    您可以使用reduceObject.entries 来获得所需的输出:

    const person = [{PersonIds: "6",TypeIds: "2",VekilIds: "6"},{PersonIds: "4",TypeIds: "27",VekilIds: "11"}];
    
    const result = person.reduce((a,e,i,s)=>{
        Object.entries(e).forEach(([k,v])=>{
             (a[k]??=[]).push(v);
             a[k] = i==s.length-1 ? a[k].join(',') : a[k]
        });
        return a;
    },{});
    
    console.log([result]);

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      • 2019-07-30
      • 2019-12-02
      相关资源
      最近更新 更多