Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

238
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda