Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

296
Visualizações
How to get array of objects only if array values matches with object array key

I have array arr1, arr2, arr3 and object array objarr

I would like to get array of objects based on condition

i.e when passing arr1, object array objarr should return only matched keys of arr1

i.e when passing arr2, object array objarr should return only matched keys of arr2 (if wrk is passed parameter only show that is true )

i.e when passing arr3, object array objarr should return only matched keys of arr3

var arr1=["name", "place"]
var arr2=["details", "wrk"]
var arr3=["name"]

var objarr=[
  {id:1, name: "ayan", place: "MY", details: "finance" , wrk: true},
  {id:2, name: "mike", place: "AU", details: "teaching", wrk: false },
  {id:3, name: "john", place: "DE", details: "service" , wrk: true}
]

function outputData(arr1){
  var final=[];
  var result = objarr.map(e=>{
   if(arr1.includes(Object.keys(e)){
    final.push(e)
   }
  })

return  final
;}

Expected Output;
//for arr1 is passed
[
  {name: "ayan", place: "MY"},
  {name: "mike", place: "AU"},
  {name: "john", place: "DE"}
]

//for arr2 is passed
[
  {details: "finance", wrk:true},
  {details: "service", wrk: true}
]

//for arr3 is passed
[
  {name: "ayan"},
  {name: "mike"},
  {name: "john"}
]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

var arr1 = ["name", "place"];
var arr2 = ["details", "wrk"];
var arr3 = ["name"];

var objarr = [
  { id: 1, name: "ayan", place: "MY", details: "finance", wrk: true },
  { id: 2, name: "mike", place: "AU", details: "teaching", wrk: false },
  { id: 3, name: "john", place: "DE", details: "service", wrk: true }
]

function outputData(arr) {
  var final = [];
  objarr.forEach(obj => {
      const temp = {};
      arr.forEach(key => {
          if(obj[key]){
              temp[key]= obj[key];
          }
      });
      if(Object.keys(temp).length===arr.length){
      final.push(temp);}
  });

  return final;
}
console.log('arr1',outputData(arr1));
console.log('arr2',outputData(arr2));
console.log('arr3',outputData(arr3));

about 4 years ago · Juan Pablo Isaza Relatório

0

Since you need to select only specific nodes from objarr, going for Array.map willnot give the result. Use Some other looping logic for that.

I used Array.reduce here.

Logic

  • Loop through objarr with Array.reduce.
  • Loop through the paremeter array inside the reduce.
  • Check if the value for each node from the parameter array in the object in objarr array.
  • If the value is truthy, add that to an object.
  • If the length of keys of this object is same as the length of parameter array, push this object to accumulator.

Please Note: This logic checks truthy value for key "wrk" only. If you want to check for all boolean values, you can use the condition added as comment just above the if statement

var arr1 = ["name", "place"]
var arr2 = ["details", "wrk"]
var arr3 = ["name"]

var objarr = [
  { id: 1, name: "ayan", place: "MY", details: "finance", wrk: true },
  { id: 2, name: "mike", place: "AU", details: "teaching", wrk: false },
  { id: 3, name: "john", place: "DE", details: "service", wrk: true }
]

function outputData(arr) {
  var result = objarr.reduce((acc, currNode) => {
    const resp = {};
    arr.forEach((option) => {
      // Current condition is only for "wrk"
      // To check truthy state for all boolean variables use the below condition
      // ((typeof currNode[option] === "boolean" && currNode[option]) || typeof currNode[option] !== "boolean")
      if ((option === "wrk" && currNode[option]) || option !== "wrk") {
        resp[option] = currNode[option]
      }
    })
    if(Object.keys(resp).length === arr.length) {
      acc.push(resp)
    }
    return acc
  }, []);
  return result;
}
console.log(outputData(arr1));
console.log(outputData(arr2));
console.log(outputData(arr3));

about 4 years ago · Juan Pablo Isaza Relatório

0

You can easily achieve the result using reduce and for..of loop

var arr1 = ["name", "place"];
var arr2 = ["details", "wrk"];
var arr3 = ["name"];

var objarr = [
  { id: 1, name: "ayan", place: "MY", details: "finance", wrk: true },
  { id: 2, name: "mike", place: "AU", details: "teaching", wrk: false },
  { id: 3, name: "john", place: "DE", details: "service", wrk: true },
];

function getData(target, source) {
  return target.reduce((acc, curr) => {
    const obj = {};
    for (let prop of source) {
      obj[prop] = curr[prop];
    }
    if (Object.keys(obj).includes("wrk")) {
      if (obj["wrk"]) acc.push(obj);
    } else acc.push(obj);
    return acc;
  }, []);
}

console.log(getData(objarr, arr1));
console.log(getData(objarr, arr2));
console.log(getData(objarr, arr3));
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda