这个问题可能会被否决,但只是询问我的知识...

我现在所拥有的:

data = {COLUMN1: "DATA1", COLUMN2: "DATA2", COLUMN3: "DATA3", ..., COLUMNn: "DATAn"};

keyColumns = ["COLUMN2", "COLUMN5", "COLUMN9"];

keyValueMap = {};


我想得到什么:

keyValueMap = {COLUMN2: "DATA2", COLUMN5: "DATA5", COLUMN9: "DATA9"};


我尝试过的

if (keyColumns.length > 0)
    {
      keyColumns.forEach(a => {
        keyvaluemap[a] = data[a];

      });
    };


我知道我不能做keyvaluemap [a] = data [a],因为keyvaluemap只是一个对象。我该如何设计它,使其获得我想要的所有价值对?直到运行时才能知道keyColumns中的值列表。

最佳答案

您可以使用Arrays的.reduce()方法:



let data = {COLUMN1: "DATA1", COLUMN2: "DATA2", COLUMN3: "DATA3", COLUMN4: "DATA4",COLUMN5: "DATA5", COLUMN9: "DATA9"},
    keyColumns = ["COLUMN2", "COLUMN5", "COLUMN9"];

let reducer = (obj, arr) => arr.reduce((a, c) => (a[c] = obj[c], a), {});

console.log(reducer(data, keyColumns));

09-15 11:44