[javascript] get one item from an array of name,value JSON

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

This question is related to javascript jquery json

The answer is


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.


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.

_x000D_
_x000D_
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
arr.push({name:"k1", value:"def"});_x000D_
_x000D_
var item;_x000D_
_x000D_
// find the first occurrence of item with name "k1"_x000D_
item = arr.find(item=>item.name=="k1");_x000D_
console.log(item);_x000D_
_x000D_
// find all occurrences of item with name "k1"_x000D_
// now item is an array_x000D_
item = arr.filter(item=>item.name=="k1");_x000D_
console.log(item);
_x000D_
_x000D_
_x000D_

Find indices

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

_x000D_
_x000D_
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
arr.push({name:"k1", value:"def"});_x000D_
_x000D_
var idx;_x000D_
_x000D_
// find index of the first occurrence of item with name "k1"_x000D_
idx = arr.findIndex(item=>item.name == "k1");_x000D_
console.log(idx, arr[idx].value);_x000D_
_x000D_
// find indices of all occurrences of item with name "k1"_x000D_
// now idx is an array_x000D_
idx = arr.map((item, i) => item.name == "k1" ? i : '').filter(String);_x000D_
console.log(idx);
_x000D_
_x000D_
_x000D_


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

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:

_x000D_
_x000D_
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
_x000D_
var found = arr.filter(function(item) { return item.name === 'k1'; });_x000D_
_x000D_
console.log('found', found[0]);
_x000D_
Check the console.
_x000D_
_x000D_
_x000D_

You can see a list of supported browsers here.

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


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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?