-1

I have a master list to refer and filter from:

nvMaster: [
    {"1": "One"},
    {"2": "TWO"},
    {"3": "THREE"},
    {"4":"FOUR"},
    {"5":"FIVE"}

];

I have second array of permitted values form final JSON.

nvPermitted:["1","3","5"];

I need to form a final array like below:

nvFinal: [
    {"1": "One"},       
    {"3": "THREE"},
    {"5":"FIVE"}
];

Any help on this is highly appreciated.

NewbieAngular
  • 51
  • 3
  • 11
  • Can you share what you've tried? I'm removing the Angular tag as this is just a TS problem. Thanks. – ggorlen Nov 04 '19 at 16:52
  • 1
    This code `nvPermitted:{"1","3","5"};` is not valid – Dalorzo Nov 04 '19 at 16:53
  • @ggorlen if it is Angular not angularJS this will subject to typescript not Javascript – Dalorzo Nov 04 '19 at 16:54
  • Possible duplicate of [Filter object properties by key in ES6](https://stackoverflow.com/questions/38750705/filter-object-properties-by-key-in-es6) – ggorlen Nov 04 '19 at 16:54
  • @Dalorzo excellent point, updated. – ggorlen Nov 04 '19 at 16:55
  • nvPermitted is updated in the post...Thanks. – NewbieAngular Nov 04 '19 at 17:14
  • Tried -> const nvFinal = Object.keys(this.nvMaster) .filter(key => this.nvPermitted.includes(key)) .reduce((obj, key) => { obj[key] = this.nvMaster[key]; // console.log("json:",JSON.stringify(obj)) return obj; }, {}); This gives issue @includes(key) ->arguement of type string is not assignable to to parameter of type '"1" | "3" | "5" – NewbieAngular Nov 04 '19 at 17:42

1 Answers1

0

You may want to refactor your code like that

nvMaster: [
    "One",
    "TWO",
    "THREE",
    "FOUR",
    "FIVE"
];
nvPermitted:[0, 2, 4]; // arr start at 0
nvFinal: nvMaster.reduce((acc, val, idx) => {
    if (nvPermitted.indexOf(idx) > -1) {
        acc[idx + 1] = val;
    }
    return acc;
}, {}); 
Alexis
  • 1
  • 1