get one item from an array of name,value JSON

I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter:

var arr = [];
arr.push({name:"k1", value:"abc"});
arr.push({name:"k2", value:"hi"});
arr.push({name:"k3", value:"oa"});

var found = arr.filter(function(item) { return item.name === 'k1'; });

console.log('found', found[0]);
Check the console.

You can see a list of supported browsers here.

In the future with ES6, you'll be able to use array.find.


Arrays are normally accessed via numeric indexes, so in your example arr[0] == {name:"k1", value:"abc"}. If you know that the name property of each object will be unique you can store them in an object instead of an array, as follows:

var obj = {};
obj["k1"] = "abc";
obj["k2"] = "hi";
obj["k3"] = "oa";

alert(obj["k2"]); // displays "hi"

If you actually want an array of objects like in your post you can loop through the array and return when you find an element with an object having the property you want:

function findElement(arr, propName, propValue) {
  for (var i=0; i < arr.length; i++)
    if (arr[i][propName] == propValue)
      return arr[i];

  // will return undefined if not found; you could return a default instead
}

// Using the array from the question
var x = findElement(arr, "name", "k2"); // x is {"name":"k2", "value":"hi"}
alert(x["value"]); // displays "hi"

var y = findElement(arr, "name", "k9"); // y is undefined
alert(y["value"]); // error because y is undefined

alert(findElement(arr, "name", "k2")["value"]); // displays "hi";

alert(findElement(arr, "name", "zzz")["value"]); // gives an error because the function returned undefined which won't have a "value" property

Find one element

To find the element with a given name in an array you can use find:

arr.find(item=>item.name=="k1");

Note that find will return just one item (namely the first match):

{
  "name": "k1",
  "value": "abc"
}

Find all elements

In your original array there's only one item occurrence of each name.

If the array contains multiple elements with the same name and you want them all then use filter, which will return an array.

var arr = [];
arr.push({name:"k1", value:"abc"});
arr.push({name:"k2", value:"hi"});
arr.push({name:"k3", value:"oa"});
arr.push({name:"k1", value:"def"});

var item;

// find the first occurrence of item with name "k1"
item = arr.find(item=>item.name=="k1");
console.log(item);

// find all occurrences of item with name "k1"
// now item is an array
item = arr.filter(item=>item.name=="k1");
console.log(item);

Find indices

Similarly, for indices you can use findIndex (for finding the first match) and filter + map to find all indices.

var arr = [];
arr.push({name:"k1", value:"abc"});
arr.push({name:"k2", value:"hi"});
arr.push({name:"k3", value:"oa"});
arr.push({name:"k1", value:"def"});

var idx;

// find index of the first occurrence of item with name "k1"
idx = arr.findIndex(item=>item.name == "k1");
console.log(idx, arr[idx].value);

// find indices of all occurrences of item with name "k1"
// now idx is an array
idx = arr.map((item, i) => item.name == "k1" ? i : '').filter(String);
console.log(idx);

To answer your exact question you can get the exact behaviour you want by extending the Array prototype with:

Array.prototype.get = function(name) {
    for (var i=0, len=this.length; i<len; i++) {
        if (typeof this[i] != "object") continue;
        if (this[i].name === name) return this[i].value;
    }
};

this will add the get() method to all arrays and let you do what you want, i.e:

arr.get('k1'); //= abc

You can't do what you're asking natively with an array, but javascript objects are hashes, so you can say...

var hash = {};
hash['k1'] = 'abc';
...

Then you can retrieve using bracket or dot notation:

alert(hash['k1']); // alerts 'abc'
alert(hash.k1); // also alerts 'abc'

For arrays, check the underscore.js library in general and the detect method in particular. Using detect you could do something like...

_.detect(arr, function(x) { return x.name == 'k1' });

Or more generally

MyCollection = function() {
  this.arr = [];
}

MyCollection.prototype.getByName = function(name) {
  return _.detect(this.arr, function(x) { return x.name == name });
}

MyCollection.prototype.push = function(item) {
  this.arr.push(item);
}

etc...