1

How can I filter an Object's field by an string array?

eg.

catValues:{
    "1":{
        value:10,
        code:5
     },
    "3":{
        value:10,
        code:5
     },
    "5":{
        value:10,
        code:5
     }
}


var chosenCats = ["1","5"]

result: {"1":{value:10, code:5}, "5":{value:10, code:5}}
0

2 Answers 2

1

You create a new object and insert just the chosen cat values.

var chosenCatValues = {};

for (var cat of chosenCats) {
  chosenCatValues[cat] = catValues[cat];
} 

Or you can use filter() and reduce():

var chosenCatValues = Object.keys(catValues)
  .filter(key => chosenCats.includes(key))
  .reduce((obj, key) => {
    obj[key] = catValues[key];
    return obj;
  }, {});

Demo:

var catValues = {
  "1": {
    value: 10,
    code: 5
  },
  "3": {
    value: 10,
    code: 5
  },
  "5": {
    value: 10,
    code: 5
  }
};

var chosenCats = ["1", "5"];

var chosenCatValues = Object.keys(catValues)
  .filter(key => chosenCats.includes(key))
  .reduce((obj, key) => {
    obj[key] = catValues[key];
    return obj;
  }, {});

console.log(chosenCatValues);

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

Comments

0

Try this:

Note: This will work with array of strings as well considering they are numbers.

var catValues = {
    "1":{
        value:10,
        code:5
     },
    "3":{
        value:10,
        code:5
     },
    "5":{
        value:10,
        code:5
     }
}

var chosen = ['1','5'];

const func = (chosen, catValues) => {
    var ch = {};
    chosen.map(chose => {
      if(chose in catValues) {
        ch[chose] = catValues[chose]
      }
  })
  return ch
}

console.log(func(chosen, catValues))

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.