4

Trying to merge duplicate keys of json array and build respective values in csv format.

A=[{a:1,b:2},{a:1,b:1},{a:1,b:6},{a:2,b:5},{a:2,b:3}]

Trying to convert in

A=[{a:'1',b:'2,1,6'},{a:2,b:'5,3'}]

code Which i tried

var existingIDs = [];
        A= $.grep(A, function (v) {
            if ($.inArray(v.a, existingIDs) !== -1) {
                return v.b+= ',';
            }
            else {
                existingIDs.push(v.a);
                return true;
            }
        });

the output is returns like

A=[{a:1,b:2},{a:1,b:'1,'},{a:1,b:'6,'},{a:2,b:5},{a:2,b:'3,'}]
1
  • Please care to comment.... down voters Commented Oct 1, 2013 at 13:56

1 Answer 1

2

Create a temporary object with 1, 2 etc from a as keys and keep adding on the b values, then iterate over that object creating the new array :

var A = [{a:1,b:2},{a:1,b:1},{a:1,b:6},{a:2,b:5},{a:2,b:3}];
var temp = {};

for (var i=0; i<A.length; i++) {
    temp[A[i].a] =
        temp[A[i].a] === undefined ?
            A[i].b :
            temp[A[i].a] + ',' + A[i].b;
}

A = [];

for (var key in temp) {
    A.push({a: key, b:temp[key]})
}

FIDDLE

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

Comments

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.