I have a json array this way
var simple = [];
for (var i = 0; i < 5; i++) {
simple.push({ id: id, name: name, mobile: mobile });
}
And the values from this json array look like this:
[{id:1
name:"Test"
mobile:100},
{id:2
name:"Test"
mobile:200},
{id:3
name:"Temp"
mobile:300},
{id:4
name:"Test"
mobile:400},
{id:5
name:"Temp"
mobile:500}]
What I need to do is compare the entries in the json array based on the "name" key.
When comparing, if record1.name = record2.name, then I need to delete the entire record1 and add the "mobile" value of record1 with record2, this way.
This is the expected end result.
[{id:1
name:"Test"
mobile:100,200,400},
{id:2
name:"Temp"
mobile:300,500}]
I tried to remove this path. But unable to add "mobile" key values to each other.
var removeItem = name;
alert('Array before removing the element = ' + simple);
simple = jQuery.grep(simple,
function(value) { return value != removeItem; });
alert('Array before removing the element = ' + simple);
Can someone help me with this?
thank
Edit ======
I tried to answer No. 1 = cited Ismail Kuruka below,
Works great with existing IE keys if new bottom entry keys are added,
var input =
[{
id:1,
name:"Test",
ssn:1,
mobile:100,
address:"A"
},
{
id:2,
name:"Test1",
ssn:2,
mobile:200,
address:"B"
},
{
id:3,
name:"Temp",
ssn:3,
mobile:300,
address:"C"
},
{
id:4,
name:"Test2",
ssn:4,
mobile:400,
address:"D"
},
{
id:5,
name:"Temp1",
ssn:5,
mobile:500,
address:"E"
}];
"" , ,
"ssn" 1, "name": "test"
[{"id":1,"name":"Test","ssn":"Test","mobile":"100"},{"id":2,"name":"Test1","ssn":"Test1","mobile":"200"},{"id":3,"name":"Temp","ssn":"Temp","mobile":"300"},{"id":4,"name":"Test2","ssn":"Test2","mobile":"400"},{"id":5,"name":"Temp1","ssn":"Temp1","mobile":"500"}]
,
var intermediateObject = {};
for(var i = 0; i < input.length; i++) {
if(typeof intermediateObject[input[i].name] == 'undefined') {
intermediateObject[input[i].name] = [];
}
else if(typeof intermediateObject[input[i].ssn] == 'undefined') {
intermediateObject[input[i].ssn] = [];
}
intermediateObject[input[i].name].push(input[i].mobile);
intermediateObject[input[i].ssn].push(input[i].mobile);
}
var outputObject = [];
var index = 1;
for(elem in intermediateObject ) {
outputObject.push({
id: index++,
name: elem,
ssn : elem,
mobile: intermediateObject[elem].join(",")
});
}
console.log(JSON.stringify(outputObject));
. - .
Output should be,
[{
id:1,
name:"Test",
ssn:1,
mobile:100,
address:"A"
},
{
id:2,
name:"Test1",
ssn:2,
mobile:200,
address:"B"
},
{
id:3,
name:"Temp",
ssn:3,
mobile:300,
address:"C"
},
{
id:4,
name:"Test2",
ssn:4,
mobile:400,
address:"D"
},
{
id:5,
name:"Temp1",
ssn:5,
mobile:500,
address:"E"
}];
?