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

162
Visualizações
Add key/value pair to object within array of arrays?

Given the following structure:

const data = {
  "show": "Family Guy",
  "characters": [
      [{name: 'Peter', age: 40, city: 'Quahog'}],
      [{name: 'Louis', age: 30}],
      [{name: 'Chris', age: 16}],
      [{name: 'Stewie', age: 1}]
    ]
 }

How can we add to each character the key/value pair of city: 'Quahog' so the output looks as follows:

const item = {
  "show": "Family Guy",
  "characters": [
      [{name: 'Peter', age: 40, city: 'Quahog'}],
      [{name: 'Louis', age: 30, city: 'Quahog'}], // city added
      [{name: 'Chris', age: 16, city: 'Quahog'}], // city added
      [{name: 'Stewie', age: 1, city: 'Quahog'}]  // city added
    ]
 }

We tried using:

let city = data.characters.[0][0].city;
costs = _.map(items, (itemArray) => {
            items = _.map(itemArray, (item) => {
              if(!item.city) {
                item.city = city;
              }
        });

But it's not working as intended and we can't get the desired output. Any idea how to accomplish this?

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

0

Not sure about the reason for having these single item arrays but this solution will do the work (I'll recommend you take a look at the process that creates this data format which is a little weird)

const data = {
  "show": "Family Guy",
  "characters": [
      [{name: 'Peter', age: 40, city: 'Quahog'}],
      [{name: 'Louis', age: 30}],
      [{name: 'Chris', age: 16}],
      [{name: 'Stewie', age: 1}]
    ]
 }
 
 const city = data.characters.find(characters => characters.find(character => character.city))[0].city

const dataWithCities = {
 ...data,
 characters: data.characters.map(characters => characters.map(character => character.city ? character : {...character, city}))
 }
 
 console.log(dataWithCities)

about 4 years ago · Juan Pablo Isaza Relatório

0

Here is another way of doing it with .reduce():

const data = {
  "show": "Family Guy",
  "characters": [
  [{name: 'Peter', age: 40, city: 'Quahog'}],
  [{name: 'Louis', age: 30}],
  [{name: 'Chris', age: 16}],
  [{name: 'Stewie', age: 1}]
]
 };

data.characters.reduce((a,c)=>
 (c[0].city=a[0].city,a));

console.log(data);

When using .reduce() without a second argument it will pick up the first array element as the initial value which is then used as a template to copy the .city property to all the other elements. The actual return value of the .reduce() method is discarded but the input array itself (data) is modified in the process and is then shown in the console.log() expression.

about 4 years ago · Juan Pablo Isaza Relatório

0

try this one

let city = data.characters.[0][0].city;
let newdata = [];
data.characters.map(items, (itemArray) => {
        items = _.map(itemArray, (item) => {
          if(item.city === undefined) {
              newdata.push({...item , city});
          } else { 
           newdata.push({...item});
           }

    })
    costs = {...newdata}
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