如何在JS中替换字典的值

时间:2017-12-03 14:16:17

标签: javascript arrays dictionary

这不是创建一个新词典,并且每次调用getVal函数时都能替换它的值吗?

<?php
include "vendor/autoload.php";
....
and continue your actual program
and is trully must to end the lines with ;
...
?

2 个答案:

答案 0 :(得分:0)

function getVal(inarr, element, data) {
    var arr = inarr[element].map((item) => item[data]);
    return arr;
};

console.log(getVal(event, 'foo', 'bar'));

答案 1 :(得分:0)

它的猜测工作充其量是因为你的问题不清楚,缺少输入,但你可以尝试这样的事情:

&#13;
&#13;
    //keys is an array of string or function
    // if it's a function then it will pass current object
    // to that function
    function getMember(object,keys){
      return keys.reduce(
        function(acc,key){
          if(acc===undefined){
            return acc;
          }
          if(typeof key === "function"){
            return key(acc);
          }
          return acc[key];
        }
        ,object
      )
    }

    function getVal(object) {
      return getMember(
        object,
        [
          "foo", // get member foo is an array of {bar:number}
          function(x){ //map array of {bar:number} to array of number
            return x.map(
              function(x){
                return x.bar; 
              });
          }
        ]
      );
    };
    var event = {
      foo:[
        {
          bar:1
        },
        {
          bar:2
        }
      ]
    };
    console.log(getVal(event));// should log [1,2]
&#13;
&#13;
&#13;