0

I want to get the value of a key in a array.

arr= [
{key: "a", label: "Adam", value: "121"},
{key: "e", label: "TT", value: "44"},
{key: "ad", label: "RRR", value: "555"}
]
arr2 = ["a","e","ad"];
arr2.map((item) => {
        //here value of item could be oneof the values in arr2
        //say its "a"
        //how do I get the value of key-"label" corresponding to the value in item???
        // in this case the value of label returned should be "Adam"
       result = get(arr, [item, "label"]); // is this possible??
      });

Any ideas on this?? Thanks!

user1234
  • 3,000
  • 4
  • 50
  • 102

4 Answers4

3

You could find the entry in arr, but do note that would be inefficient:

arr2.map(item => arr.find(e => e.key === item).label)

A better solution would involve converting arr to a map where the keys are taken from the key property of each object.

Kraylog
  • 7,383
  • 1
  • 24
  • 35
2

arr= [
{key: "a", label: "Adam", value: "121"},
{key: "e", label: "TT", value: "44"},
{key: "ad", label: "RRR", value: "555"}
]
arr2 = ["a","e","ad"];

result = arr2.map(x => arr.find(y => y.key === x).label);

console.log(result);
curlyBraces
  • 1,095
  • 8
  • 12
2

Make a another array to push each label in each iteration of keys

arr= [
{key: "a", label: "Adam", value: "121"},
{key: "e", label: "TT", value: "44"},
{key: "ad", label: "RRR", value: "555"}
]
arr2 = ["a","e","ad"];
var getLable = [];
var keys = arr.map((e)=>e.key);
arr2.map((item) => {
 var index = keys.indexOf(item);
 getLable.push(arr[index].label);
});
console.log(getLable);
freelancer
  • 1,174
  • 5
  • 12
1

Yes it is possible,please execute the code given below as it is and let me know if you have got the desired output

arr= [
      {key: "a", label: "Adam", value: "121"},
      {key: "e", label: "TT", value: "44"},
      {key: "ad", label: "RRR", value: "555"}
     ]

    arr2 = ["a","e","ad"];


    // get method returns the particular object 
    // and the required property (as mentioned in) propertyRequired
    var get =function (arr, item, propertyRequired) 
    {

      var result = arr.filter(function( obj ) {
                            return obj.key == item;
                   });

      // Since propertyRequired is a string
      // we can acess it only in this way
      // and not using . operator 
      //  obj.["key"] 
      return result[0][propertyRequired];

    }

   arr2.map((item) => {

     result = get(arr, item, "label"); // is this possible??
     console.log(result);

   });

Please refer these links:

Get JavaScript object from array of objects by value or property

How to convert string as object's field name in javascript