将对象数组转换为一个逗号分隔的对象

时间:2019-04-22 17:40:41

标签: javascript arrays

我在数组下面

const arr =

0: Object { 1: 1, 6: 1, 11: 1, … }
1: Object { 2: "3", 7: "", 12: "", … }
2: Object { 3: "3", 8: "", 13: "", … }
3: Object { 4: "", 9: "", 19: "3", … }
4: Object { 5: "4", 10: "", 15: "", … }

我希望它像非空值一样转换它

  

{1:2,6:1,11:1,2:3,3:3,19:3,5:4}

我尝试了以下解决方案:

let result = JSON.stringify(arr).replace(/(\[)(.+)(\])/g, "{$2}");

但是我得到的结果是

{{"1":1,"6":1,"11":1,"16":1},{"2":"3","7":"","12":"","17":""},{"3":"3","8":"","13":"","18":""},{"4":"","9":"","14":"","19":"3"},{"5":"4","10":"","15":"","20":""}}

请协助获得所需的答复。

4 个答案:

答案 0 :(得分:2)

以下是帮助您入门的摘要。对于重复的键,将保留后面的键,但是如果这不是您期望的行为,则可以添加一个简单的if条件来保留第一次出现或根据需要进行处理。

let arr = [
  {1: 1, 6: 1, 11: 1,},
  {2: "3", 7: "", 12: "",},
  {3: "3", 8: "", 13: "",},
  {4: "", 9: "", 19: "3",},
  {5: "4", 10: "", 15: "",},
];

let output = {};
arr.forEach(a => Object.entries(a)
    .filter(([, value]) => value)
    .forEach(([key, value]) => output[key] = value));

console.log(output);

答案 1 :(得分:2)

因此,您需要遍历所有索引,然后遍历所有键并查看它们是否具有值。

var arr = [
  { 1: 1, 6: 1, 11: 1},
  { 2: "3", 7: "", 12: ""},
  { 3: "3", 8: "", 13: ""},
  { 4: "", 9: "", 19: "3"},
  { 5: "4", 10: "", 15: ""}
]

var out = arr.reduce((result, obj) => {
  Object.entries(obj).forEach(([key, value]) => {
    if (value !== "") {
      result[key] = Number(value)
    }
  })
  return result
}, {})

console.log(JSON.stringify(out))

答案 2 :(得分:2)

一种可能的解决方案是使用Array.reduce()生成一个新的object。在下一个解决方案中,如果内部对象之间存在共享密钥,则最新的value将存储在最后一个object上。为了将字符串强制转换为数字,我们使用unary plus运算符:

const arr = [
  {1: 1, 6: 1, 11: 1},
  {2: "3", 7: "", 12: ""},
  {3: "3", 8: "", 13: ""},
  {4: "", 9: "", 19: "3"},
  {5: "4", 10: "", 15: ""}
];

let res = arr.reduce((acc, obj) =>
{
    Object.entries(obj).forEach(([k, v]) =>
    {
        if (v !== "") acc[k] = +v;
    });

    return acc;
}, {});

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

答案 3 :(得分:1)

如果订单无关紧要,这将为您提供所需的解决方案:

const arr = [
  { 1: 1, 6: 1, 11: 1 },
  { 2: "3", 7: "", 12: "" },
  { 3: "3", 8: "", 13: "" },
  { 4: "", 9: "", 19: "3" },
  { 5: "4", 10: "", 15: ""}
];

let reduced = arr.reduce((acc, val) => {
  Object.assign(acc,
    Object.keys(val)
    .filter(key => val[key])
    .reduce((res, key) => (res[key] = +val[key], res), {})
  );
  return acc;
}, {});

console.log(JSON.stringify(reduced));