0

I have an array that contains two objects with Key Value Pairs.

Object 1 : Key: "FirstObj" Value: "xyz" 
Object 2 : Key: "SecondObj" Value: "abc"

I want to know how can I retrieve the value of array with Key FirstObj?

Tried this so far:

var getKeyValue= [];
 for(var i=0;i<myChartArray.length;i++)
 {
     getKeyValue.push(myChartArray[i]["FirstObj"]);

 }
Fact Finder
  • 171
  • 3
  • 5
  • 15

5 Answers5

2

You can use Array.prototype.find:

let firstObj = myChartArray.find(item => item.Key === 'FirstObj');
console.log(firstObj.Value);

Note that this code uses ES6 features.

str
  • 42,689
  • 17
  • 109
  • 127
1

Adding to the answer of str, this is how you'd do it without ES6:

function getFirstObj(myChartArray){
    for(var i=0; i < myChartArray.length; i++){
       if (myChartArray[i].Key === 'FirstObj'){
           return myChartArray[i]
       }
    }
}
Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
0

If you don't want to use ES6 you could use Array.prototype.filter().

The function would look something like this:

var yourValue = yourArray.filter(function(object) {

  return object.Key === 'FirstObj';

})[0].Value; 

The variable yourValue will then contain the value you were looking for.


Alternatively if you just need to solve this particular case and you are not looking for an iterative, scalable solution. You can just select the object and value statically. This assumes you can be sure of the order of objects in your array. If the above is true for you, you can just do this:

var value = youArray[0].Value;

bbop99
  • 1,625
  • 1
  • 11
  • 25
0

You can get it using filter()

var array = [];
array.push({Key:"FirstObj", Value:"xyz"});
array.push({Key:"SecondObj", Value:"abc"});


var found = array.filter(function(item) { return item.Key === "FirstObj"; });

console.log(found[0]);
M. Wiśnicki
  • 6,094
  • 3
  • 23
  • 28
  • 2
    It's a nice solution which makes good sense in most cases, but beware that this will traverse the entire `Array`, instead of stopping after finding the value, which can be costly if the `Array` is very long. – Luka Jacobowitz Dec 29 '16 at 12:11
0

You can use array#find():

var array = [{Key:"FirstObj", Value:"xyz"}, {Key:"SecondObj", Value:"abc"}],
    found = array.find(function(elem) { 
      return elem.Key === "FirstObj"; 
    });

console.log(found);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46