0

I'm looking for an elegant way to do the following:

I have a JS object:

     var sObject = {};
     sObject[Col1] = "Value1";
     sObject[Col2] = "Value2";
     sObject[Col2] = "Value3";

I also have an array

     var arrayCols=[];
     arrayCols.push("Col2");

What I am trying to do is remove all the key/values from sObject where Key != arrayCols key

Once the needful is done, my sObject should only contain Col2:Value2 as Col2 is the only key in the arrayCols

I'm trying something along the lines of:

var sObject = {};
sObject['Col1'] = "Value1";
sObject['Col2'] = "Value2";
sObject['Col2'] = "Value3";

var arrayCols = [];
arrayCols.push("Col2");

let newObject = {};

for (const [key, value] of Object.entries(sObject)) {
  if (key in arrayCols) {
    newObject[key] = value;
  }
}

console.log(newObject);
isherwood
  • 58,414
  • 16
  • 114
  • 157
Shrimp2022
  • 51
  • 8
  • 2
    Note that I added quotes to your object key names in lines 2-4. – isherwood Feb 09 '22 at 20:49
  • You can try to use filter - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – Subir Kumar Sao Feb 09 '22 at 20:50
  • @isherwood doesn't that change the issue? – evolutionxbox Feb 09 '22 at 20:59
  • Not really. There's no indication that those are variable values, and the array value implies that they were supposed to be strings. At any rate, I made it known so the question author could make corrections but the demo works without error. – isherwood Feb 09 '22 at 21:01

2 Answers2

2

You can use Object.fromEntries and map:

var obj = { Col1: "Value1",  Col2: "Value2",  Col3: "Value3" };
var cols = ["Col2"];

var result = Object.fromEntries(cols.map(col => [col, obj[col]]));

console.log(result);
trincot
  • 317,000
  • 35
  • 244
  • 286
1

E. g. using reduce:

var sObject = {};
sObject.Col1 = "Value1";
sObject.Col2 = "Value2";
sObject.Col2 = "Value3";

var arrayCols = [];
arrayCols.push("Col2");

sObject = arrayCols.reduce((a, k) => (a[k] = sObject[k], a), {})


console.log(sObject)
Kosh
  • 16,966
  • 2
  • 19
  • 34