首页 > 解决方案 > 如何在 JS 中对数组进行非规范化

问题描述

我有以下形式的数据集

let data = [
  {
    "id": {
      "primary": "A1"
    },
    "msg": 1
  }, {
    "id": {
      "primary": "A1"
    },
    "msg": 2
  }, {
    "id": {
      "primary": "B2"
    },
    "msg": 3
  }
]

我想将其转换为

newData = [
  {
    "id": {
      "primary": "A1"
    },
    "items": [
      { "msg": 1 },
      { "msg": 2 }
    ]
  },
  {
    "id": {
      "primary": "B2"
    },
    "items": [
      { "msg": 3 }
    ]
  }
]

我认为该方法类似于以下内容,但不确定undefined在这种情况下如何检查值。

let newData = [];
for (let i = 0; i < data.length; i++) {
  if (newData[i]['id']['primary'] === data[i]['id']) newData.push(data[i]['id'])
  else newData[i]['items'].push(data[i]['msg'])
}

如何转换原始数据集以合并具有匹配项的条目primary id

标签: javascriptarraysdenormalization

解决方案


一种选择是使用.reduce()从现有数组创建一个新数组。

我添加了评论以澄清。

let data = [ { "id": { "primary": "A1" }, "msg": 1 }, { "id": { "primary": "A1" }, "msg": 2 }, { "id": { "primary": "B2" }, "msg": 3 } ];

let result = data.reduce((out,item) => {
  let {id, ...items} = item;                      //Separate the "id" and "everything else"
  let existing = out.find(({id}) => id.primary == item.id.primary); 

  existing                                        //have we seen this ID already?
    ? existing.items.push(items)                  //yes - add the items to it
    : out.push({ id: {...id}, items: [items]});   //no - create it
    
  return out;
  }, []);
  
console.log(result);

几点注意事项:

  • 您可能会注意到我已经使用 设置了 ID id: {...id},尽管它id已经是一个对象。这是因为使用现有id对象会创建一个引用,而{...id}创建一个浅拷贝

  • 我没有在msg任何地方指定该属性。相反,任何未添加的属性 id将添加到items列表中(示例如下)

        let data = [ { "id": { "primary": "A1" }, "msg": 1, "otherStuff": "Hello World!" }, { "id": { "primary": "A1" }, "msg": 2, "AnotherThing": true }, { "id": { "primary": "B2" }, "msg": 3, "someOtherProperty": false } ];
    
        let result = data.reduce((out,item) => {
          let {id, ...items} = item;
          let existing = out.find(({id}) => id.primary == item.id.primary); 
    
          existing
            ? existing.items.push(items)
            : out.push({ id: {...id}, items: [items]});
            
          return out;
          }, []);
          
        console.log(result);

    也就是说,如果您开始嵌套对象(ID 除外),它们可能会被包含为引用;...items只是一个拷贝。

    如果是这种情况,请考虑像JSON.parse(JSON.stringify(...))深拷贝这样的东西。请务必阅读链接;有一些警告。


推荐阅读