-2

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'
 }];
6
  • i dont know how to create this..:-(\ Commented Jan 7, 2014 at 5:28
  • You can't create anything like this: {id: '71','86'}, it's just a syntax error. Commented Jan 7, 2014 at 5:31
  • then how like id :'71,86'??is it possible? Commented Jan 7, 2014 at 5:32
  • Yes, that is possible, or maybe {id: ['71','86']}. Commented Jan 7, 2014 at 5:35
  • yea like id :'71,86' Commented Jan 7, 2014 at 5:36

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

one doubt also what is this underscore ` var f = neu.filter(function(e, _) {`
@Sush That's the index, _ is a valid variable name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.