JSON Array根据相同的ID组合项目

时间:2017-05-09 01:48:06

标签: javascript

所以我有这些项目,它有一些重复的ID,但值不同。它可能是更多的项目,但目前我使用这些项目。数组结果如下:

"items": [
    {
        "id": "E46",
        "size": "5 Ounce"
    },
    {
        "id": "E46",
        "color": "Green"
    },
    {
        "id": "E32",
        "size": "8 Ounce"
    },
    {
        "id": "E32",
        "color": "Green"
    },
    {
        "id": "E4G",
        "size": "5 Ounce"
    },
    {
        "id": "E4G",
        "color": "Pink"
    },
    {
        "id": "E3C",
        "size": "8 Ounce"
    },
    {
        "id": "E3C",
        "color": "Pink"
    }
]

我喜欢将这些结合起来并使它看起来像这样:

"items": [
    {
        "id": "E46",
        "size": "5 Ounce"
        "color": "Green"
    },
    {
        "id": "E32",
        "size": "8 Ounce"
        "color": "Green"
    },
    {
        "id": "E4G",
        "size": "5 Ounce"
        "color": "Pink"
    },
    {
        "id": "E3C",
        "size": "8 Ounce"
        "color": "Pink"
    }
]

如果可能,谢谢:

4 个答案:

答案 0 :(得分:2)

你可以这样做:

var data = { items: 
[{ id: 'E46', size: '5 Ounce' },
 { id: 'E46', color: 'Green' },
 { id: 'E32', size: '8 Ounce' },
 { id: 'E32', color: 'Green' },
 { id: 'E4G', size: '5 Ounce' },
 { id: 'E4G', color: 'Pink' },
 { id: 'E3C', size: '8 Ounce' },
 { id: 'E3C', color: 'Pink' } ] }

var result = {}

data.items.forEach(function (item) { //1
    Object.keys(item).forEach(function(key) { //2
        if (!result[item.id]) result[item.id] = {}; //3
        result[item.id][key] = item[key]; //4
    });
})

以下是发生的事情:

// 1 我们遍历items数组

中的每个项目

// 2 我们遍历来自key数组

的个人item中的每个items

// 3 我们使用item id和空对象创建键值配对

// 4 我们添加了当前的键值对,我们的新item对象在我们的result对象中

result对象将具有此值:

{ E46: { id: 'E46', size: '5 Ounce', color: 'Green' },
  E32: { id: 'E32', size: '8 Ounce', color: 'Green' },
  E4G: { id: 'E4G', size: '5 Ounce', color: 'Pink' },
  E3C: { id: 'E3C', size: '8 Ounce', color: 'Pink' } }

如果你想把它放回一个数组中,你所要做的就是遍历对象中的每个键值对,并将所有值都添加到数组中,如下所示:

var arrayResult = []
Object.keys(result).forEach(function(key) {
    arrayResult.push(result[key])
});

然后您的arrayResult变量将具有此值:

[ { id: 'E46', size: '5 Ounce', color: 'Green' },
  { id: 'E32', size: '8 Ounce', color: 'Green' },
  { id: 'E4G', size: '5 Ounce', color: 'Pink' },
  { id: 'E3C', size: '8 Ounce', color: 'Pink' } ]

你可以在你的程序中的任何其他地方使用。

答案 1 :(得分:0)

function mergeObjectWithSameId(items) {
  let output = []
  items.forEach((item) => {
    if (output.filter(existingItem => existingItem.id === item.id).length === 0) {
      output.push(item)
    } 
    else {
      const existingItem = output.filter(existingItem => existingItem.id === item.id)[0]
      Object.keys(item).forEach(key => {
        if(!existingItem[key]) {
          existingItem[key] = item[key]
        }
      })
    }
  })
  return output
}

我已在Chrome控制台中对其进行了测试。

只需运行mergeObjectWithSameId(items)和Voila即可获得期待的结果!

答案 2 :(得分:0)

假设您正在寻找JavaScript解决方案,并且已经将问题中的'items'JSON解析为JavaScript对象(下面为itemsParsed),您可以实现数据重组分两步。

第一个是创建数据的hashmap,其中重复的'id'属性表示新Object中的键,如此...

var itemsParsed = theParsedJSON;

var itemHolder = (function() {
    var O = {}, ID;
    itemsParsed.forEach(function(o) {
        Object.keys(o).forEach(function(a) {
            if (a === 'id') {
                ID = o.id;
                if (!O[ID]) O[ID] = {};
            } else {
                O[ID][a] = o[a];
            }
        });
    });
    return O;
}());

这将返回对象itemHolder,因为......

itemHolder = {
    E46: { 
        size: "5 Ounce" 
        color: "Green" 
    } 
    E32: { 
        size: "8 Ounce" 
        color: "Green" 
    } 
    E4G: { 
        size: "5 Ounce" 
        color: "Pink" 
    } 
    E3C: { 
        size: "8 Ounce" 
        color: "Pink" 
    }
};

下一步是在另一个步骤转换中使用这个结构,从中可以创建新的对象并将其推送到新的数组中,就像这样......

var newItems = [];

Object.keys(itemHolder).forEach(function(n) {
    var tmp = itemHolder[n];
    var newObj = {
        id: n
    };
    Object.keys(tmp).forEach(function(x) {
        newObj[x] = tmp[x];
    });
    newItems.push(newObj);
});

当JSON.stringify方法应用于它时,可以看到newItems数组的结构......

console.log(JSON.stringify(newItems, null, 4));
/* ==>
[
    {
        "id": "E46",
        "size": "5 Ounce",
        "color": "Green"
    },
    {
        "id": "E32",
        "size": "8 Ounce",
        "color": "Green"
    },
    {
        "id": "E4G",
        "size": "5 Ounce",
        "color": "Pink"
    },
    {
        "id": "E3C",
        "size": "8 Ounce",
        "color": "Pink"
    }
]
*/

希望有所帮助。 :)

答案 3 :(得分:0)

您可以reduce阵列。创建一个将每个唯一的id作为键的累加器对象,并基于id

使用Object.assign()合并每个对象

const items=[{id:"E46",size:"5 Ounce"},{id:"E46",color:"Green"},{id:"E32",size:"8 Ounce"},{id:"E32",color:"Green"},{id:"E4G",size:"5 Ounce"},{id:"E4G",color:"Pink"},{id:"E3C",size:"8 Ounce"},{id:"E3C",color:"Pink"}];

const merged = items.reduce((acc, o) => {
  acc[o.id] = Object.assign(acc[o.id] || {}, o)
  return acc;
}, {})

const output = Object.values(merged)

console.log(output)