1

This question probably will be down-voted, but just asking for my knowledge...

What I have now:

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

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

keyValueMap = {};

What I want to get:

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

What I have tried:

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

      });
    };

I know that I cannot do keyvaluemap[a] = data[a], because keyvaluemap is just an object. How can I craft it so that it gets all value pairs as I wanted? The list of values in keyColumns cannot be known until runtime.

2 Answers 2

1

You can use .reduce() method of Arrays:

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

Sign up to request clarification or add additional context in comments.

Comments

1

try this solution:

const result = keyColumns.reduce((acc, cur) => !!data[cur] ? ({...acc, [cur]: data[cur]}) : acc;
}, {});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.