0

I have the json array name like as newarr.How to get the all id's from the json array and how to add with in the arr value?

 var arr=new Array();
 var newarr=new Array([
        {
            "id": 16820,
            "value": "abcd",
            "info": "Centre"
        },
        {
            "id": 18920,
            "value": "abcd-16820",
            "info": "Centre"
        },
        {
            "id": 1744,
            "value": "abcd-16820",
            "info": "Centre"
        },
        {
            "id": 16822,
            "value": "AaronsburgPA-16820",
            "info": "Centre"
        }
    ]);

5 Answers 5

2

This should do it:

for (var o in newarr){
    arr.push(newarr[o].id);
}

also, you don't need to use both square brackets and new Array when building an array object, one of the other will do:

var myarray = new Array(1,2,3);

or

var myarray = [1,2,3];
Sign up to request clarification or add additional context in comments.

Comments

1

I tried this with jQuery and here is the fiddle for it.

$.each(newarr[0], function(k, v) {
    arr.push(v.id);
});
console.log(arr);

1 Comment

jquery... lame ;) i still don't see why one wouldn't use map for that :-/
0

It's very simple:

for(prop in newArr) {
    arr.push(newArr[prop].id);
}

Allow me to suggest that instead of coming directly to Stack Overflow for help, you Google around a bit next time. :) Also, that is not a JSON array: it's a Javascript array. And it's better to initialize an array with [] notation (var arr = []).

Comments

0

Both given answers won't work, because you are creating a nested array (newarr=new Array([...])).

The algorithm is: loop through the Array containing objects, and push the value of every object.id to arr.

In you case:

for (var i=0;i<newarr[0].length;i+=1){
  if (newarr[0][i].id) {
    arr.push(newarr[0][i].id);
}

furthermore: this is not a 'JSON Array'. There are no such things as JSON Objects/Arrays

Comments

0

You can use the map method on array:

arr = newarr.map(function(obj) { return obj.id })

And a link to the documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map

If you don't have an id in every object, you might want to filter null:

arr = newarr.map(function(obj) {  
  return obj.id  
}).filter(function(id){  
  return id !== undefined  
})

Documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter

and if you really have a nested array, do this first:

newarr = newarr[0]

and here is a link to jsfiddle

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.