Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - remove duplicates from json array and combine its id's using node.js

In the following code newData print as follows

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

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' ];

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'
 }];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...