如何获得"键的价值"在一个阵列-Javasciript

时间:2018-02-10 07:42:30

标签: javascript

我想获取数组中键的值。

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

有关于此的任何想法? 谢谢!

4 个答案:

答案 0 :(得分:3)

您可以find arr中的条目,但请注意效率低下:

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

更好的解决方案是将arr转换为映射,其中键是从每个对象的key属性中获取的。

答案 1 :(得分: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);

答案 2 :(得分:2)

创建另一个数组以在每次键迭代中推送每个标签



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




答案 3 :(得分:1)

是的,有可能,请按原样执行下面给出的代码,如果您有所需的输出,请告诉我

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

   });

请参阅以下链接:

Get JavaScript object from array of objects by value or property

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