【问题标题】:JSON - array of objects into objects of arraysJSON - 将对象数组转换为数组对象
【发布时间】:2015-10-24 01:33:59
【问题描述】:

我有一系列 JSON 条目:

[{"num": "1","name_A": "Alex" ,"name_B": "Bob"}, {"num": "2","name_A": "Anne" ,"name_B": "Barbra"}]

我正在尝试尽可能轻松地将这个对象数组转换为两个对象 - 一个具有标题 name_A,第二个具有标题 name_B。对象必须包含标题和匹配的 num-name 对数组:

[{title: "name_A", names:[{"1", "Alex}, {"2", "Anne"}]}, {title:"name_B", names: [{"1", "Bob"}, {"2", "Barbra"}]}]

起初我尝试通过减少对象数组两次来简单地创建两个对象,一次用于 name_A,第二次用于 name_B,然后将所有内容粘合在一起:

// get 'names' array
var name_A = objArray.reduce(function(memo, curr) {
    memo.push({curr.num, curr.name_A})
    return memo;
}, []);

但即使这样也失败了。如果我用空数组初始化reduce,为什么备忘录没有推送方法?

第二个问题,我是在正确的轨道上还是有更好的方法来实现这一目标?

【问题讨论】:

  • { "1", "Alex" } 不是有效对象。对象元素的形式都是key: value

标签: javascript arrays json functional-programming


【解决方案1】:

内嵌评论,对预期进行了一些小的更正。

var input = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }]

var output = input.reduce(function (a, b) {
    // construct new objects and set their properties
    var i = {};
    i[b.num] = b.name_A;
    var j = {};
    j[b.num] = b.name_B;

    // add them to our collection elements
    a[0].names.push(i);
    a[1].names.push(j);

    return a;
   // initializing our collection
}, [{ title: "name_A", names: [] }, { title: "name_B", names: [] }]);

// pretty print our output
console.log(JSON.stringify(output, null, "     "))

var input = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }]

var output = input.reduce(function (a, b) {
  // construct new objects and set their properties
  var i = {};
  i[b.num] = b.name_A;
  var j = {};
  j[b.num] = b.name_B;

  // add them to our collection elements
  a[0].names.push(i);
  a[1].names.push(j);

  return a;
  // initializing our collection
}, [{ title: "name_A", names: [] }, { title: "name_B", names: [] }]);

so.log(output)
<pre id="output"></pre>
<script>
  var so = {
    log: function(o) {
      document.getElementById("output").innerHTML = JSON.stringify(o, null, "     ")
    }
  }
</script>

【讨论】:

    【解决方案2】:

    您的代码的问题是{ curr.num, curr.name_A } 不是有效对象,它缺少属性名称。我在下面的代码中添加了属性numname

    var name_A = [];
    var name_B = [];
    objArray.forEach(function(curr) {
        name_A.push({num: curr.num, name: curr.name_a});
        name_B.push({num: curr.num, name: curr.name_B});
    });
    var result = [ 
        { title: "name_A" }, names: name_A },
        ( title: "name_B" }, names: name_B }
    ];
    

    另外,如果你想用循环遍历数组的结果创建一个数组,你应该使用.map而不是.reduce

    【讨论】:

      【解决方案3】:

      假设只有属性num 是固定的。所有其他属性都被视为数据,例如 name_Aname_B

      var a = [{ "num": "1", "name_A": "Alex", "name_B": "Bob" }, { "num": "2", "name_A": "Anne", "name_B": "Barbra" }],
          result = [];
      a.forEach(function (el) {
          var num = el.num;
          Object.keys(el).forEach(function (k) {
              function tryFindIndexAndSetNames(aa, i) {
                  if (aa.title === k) {
                      result[i].names[num] = el[k];
                      return true;
                  }
              }
      
              if (k !== 'num' && !result.some(tryFindIndexAndSetNames)) {
                  var o = {};
                  o[num] = el[k];
                  result.push({ title: k, names: o });
              }
          });
      });
      document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

      【讨论】:

        猜你喜欢
        • 2016-09-19
        • 2012-07-21
        • 2020-10-02
        • 1970-01-01
        • 2018-09-12
        • 2015-10-30
        • 1970-01-01
        相关资源
        最近更新 更多