get one item from an array of name,value JSON

JavascriptJqueryJson

Javascript Problem Overview


I have this array:

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

is it possible to do get the value or a specific element by knowing the name ?

something like this:

arr['k2'].value

or

arr.get('k1')

Javascript Solutions


Solution 1 - Javascript

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:

Check the console.

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

You can see a list of supported browsers here.

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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...

Solution 6 - Javascript

I don't know anything about jquery so can't help you with that, but as far as Javascript is concerned you have an array of objects, so what you will only be able to access the names & values through each array element. E.g arr[0].name will give you 'k1', arr[1].value will give you 'hi'.

Maybe you want to do something like:

var obj = {};

obj.k1 = "abc";
obj.k2 = "hi";
obj.k3 = "oa";

alert ("obj.k2:" + obj.k2);

Solution 7 - Javascript

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

Solution 8 - Javascript

The easiest approach which I have used is

var found = arr.find(function(element) {
         return element.name === "k1";
 });
	   
//If you print the found :
console.log(found);
=> Object { name: "k1", value: "abc" }

//If you need the value
console.log(found.value)
=> "abc"

The similar approach can be used to find the values from the JSON Array based on any input data from the JSON.

Solution 9 - Javascript

If you want the name, pick the index

arr[4] //returns "cool"

If you want the index, pick the name with the find( ) method like this :

	let arr = ["abc", "hi", "oa", "cool"];

	t = arr.find(f);

	document.getElementById("ID").innerHTML = 
	"Elément = "+ t +
	"<br>Index = "+ arr.indexOf(t);

	function f(that) {  return that == "cool"; }

I picked "cool" then the return will be 3 which is the matching index.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOmuView Question on Stackoverflow
Solution 1 - JavascriptLangdonView Answer on Stackoverflow
Solution 2 - JavascriptnnnnnnView Answer on Stackoverflow
Solution 3 - Javascriptuser2314737View Answer on Stackoverflow
Solution 4 - JavascriptmythzView Answer on Stackoverflow
Solution 5 - JavascriptRobView Answer on Stackoverflow
Solution 6 - JavascriptblankaboutView Answer on Stackoverflow
Solution 7 - JavascriptAsif MunshiView Answer on Stackoverflow
Solution 8 - JavascriptAshish GirdharView Answer on Stackoverflow
Solution 9 - JavascriptAxonile PlusView Answer on Stackoverflow