User
User

Reputation: 1662

how to get particular value from json array?

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"
        }
    ]);

Upvotes: 0

Views: 3907

Answers (5)

Robert Wilson
Robert Wilson

Reputation: 669

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);

Upvotes: 1

sdepold
sdepold

Reputation: 6231

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

Upvotes: 0

KooiInc
KooiInc

Reputation: 122898

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

Upvotes: 0

codebox
codebox

Reputation: 20254

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

Upvotes: 2

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

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 = []).

Upvotes: 0

Related Questions