从json数组中删除重复项,并使用node.js合并其ID [英] remove duplicates from json array and combine its id's using node.js

查看:185
本文介绍了从json数组中删除重复项,并使用node.js合并其ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,newData打印如下

In the following code newData print as follows

var newData =(JSON.parse(jobData));
console.log(newData);

当前包含5个值.它可能会变化

currently it contains 5 values.it may varying

[{
    mode: daily,
    id: '71'
    os: 'Win37'
}, {
    mode: daily,
    id: '45'
    os: 'Win37-1'
}, {
    mode: daily,
    id: '37'
    os: 'Win64'
}, {
    mode: daily,
    id: '86'
    os: 'Win37'
},{
    mode: daily,
    id: '7'
    os: 'Win64' ];

从上面的json数组

我必须创建这样的数组,这怎么可能? 例如,用不同的id创建相同的os 'Win37'.如果存在重复的os,则按如下方式组合其ids

from the above json array i have to create array like this how it is possible? ie create same os 'Win37' with different id.If duplicate os present combine its ids as follows

MynewArray = [{
    mode: daily,
    id: '71,86'
    os: 'Win37'
 }, {
    mode: daily,
    id: '45'
    os: 'Win37-1'
 }, {
    mode: daily,
    id: '37,7'
    os: 'Win64'
 }];

推荐答案

您的代码中有语法错误,缺少,mode值的引号,更正错误后,您可以尝试以下操作, array的id属性是数组,而o此处是指原始数组.

There are syntax errors in your code, missing , and quotes for mode values, after fixing the errors, you can try the following, neu array's id properties are arrays and o here refers to the original array.

var neu = [], l = o.length;

for (var i = 0; i < l; i++) {
    var f = neu.filter(function(e, _) {
       return e.os === o[i].os;
    });   
    if (f.length) {
        f[0].id.push(o[i].id);
    } else {
        neu.push({
            os: o[i].os,
            id: [o[i].id],
            mode: o[i].mode
        });
    }
} 

jsFiddle

这篇关于从json数组中删除重复项,并使用node.js合并其ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆