2

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

4
  • 2
    Note that I added quotes to your object key names in lines 2-4. Commented Feb 9, 2022 at 20:49
  • You can try to use filter - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Feb 9, 2022 at 20:50
  • @isherwood doesn't that change the issue? Commented Feb 9, 2022 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. Commented Feb 9, 2022 at 21:01

2 Answers 2

3

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

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

Comments

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)

1 Comment

@trincot, you're right again =))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.