Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
Remove keys from object that are not in an array

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!