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

167
Visualizações
How to get only key value pairs in nested object in javascript
let Ar=[
{
      info:{
          name:"Sai",
          age:24
      },
    grade:'A'
},    
{
    name:"Satish",
    grade:'B',
    info:{
        place:"Hyd",
        company:'Company1'
    },
    info2:{
        place2:"Hyderabad",
        company2:'Company2'
    }
}

]

**Output should be key values pairs only **

[
    {
        "name": "Sai",
        "age": 24,
        "grade": "A"
    },
    {
        "name": "Satish",
        "grade": "B",
        "place": "Hyd",
        "company": "Company1",
        "place2": "Hyderabad",
        "company2": "Company2"
    }
]

How we can get only key value pairs form the object and nested object

*Current solution I have like this But do we have more optimized code to get the only key value pairs from an object. I have used Object.keys(obj) and Object.entries(obj) methods to achieve *

let fr=Ar.map((A)=>{
    let test=[];
  let en= Object.keys(A).map((item) => {
  if (typeof A[item] === "object") {
     Object.entries(A[item]).map((i)=>{test.push(i)})
  } else {
    return test.push([item, A[item]]);
  }
});  
    
    return test;
})
    
let finalAnswer=fr.map((item)=>{
    return Object.fromEntries(item)
})
 console.log("Spread Print",finalAnswer)

Is there any better solution than me?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use this

let fr=Ar.map((A)=>{
let test={};


Object.keys(A).forEach((item) => {

if (typeof A[item] === "object") {
 test={...test,...A[item]};
  } else {
test[item]=A[item]


 }

}return test });

about 4 years ago · Juan Pablo Isaza Relatório

0

The below may be one possible solution (using recursion) to achieve the desired objective.

Please note that if there are duplicate keys in nested levels, only the latest/last key-value pair will be retained.

Code Snippet

// recursive method to transform nested objects
const recTxf = parm => {
  if (Array.isArray(parm)) {    // if key-value pair array
    const [k, v] = parm;        // either recurse to nested, or return key-value pair
    if (typeof v === 'object') return recTxf(v);
    else return { [k]: v };
  } else return {               // otherwise, it is object
    ...Object.entries(parm)     // iterate over key-value pairs
      .reduce(
        (acc, itm) => ({        // use "reduce" to accumulate/aggregate
          ...acc,
          ...recTxf(itm)        // aggregate results of the recursive calls
        }),
        {}
      )
  };
};

// method to iterate over the array
const myTransform = arr => arr.map(ob => recTxf(ob));

let Ar = [
  {
    info: {
      name: "Sai",
      age: 24
    },
    grade: 'A'
  },
  {
    name: "Satish",
    grade: 'B',
    info: {
      place: "Hyd",
      company: 'Company1'
    },
    info2: {
      place2: "Hyderabad",
      company2: 'Company2'
    }
  }
];

console.log(myTransform(Ar));
.as-console-wrapper { max-height: 100% !important; top: 0 }

Explanation

Inline comments are provided in the snippet above.

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