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

239
Visualizações
How to push all items from array of object to an array?

I am trying to extract and push the elements from an array of object to an empty object. Here is the example of the arrays.

const products = ["cars", "phones", "laptops"];

const productArrayOfObj = [
  {
    cars: ["Ford", "Chevy", "Honda", "Toyota"],
  },
  {
    phones: ["iPhone", "Samsung", "Nokia", "Sony"],
  },
  {
    laptops: ["Mac", "Dell", "HP", "Acer"],
  },
];

const mappedProducts= products.map((_,i) => productArrayOfObj[i]);

From mappedProducts returns this structure, even though I am not sure if this is the correct way of mapping this.

 [ { cars: [ 'Ford', 'Chevy', 'Honda', 'Toyota' ] }, 
  { phones: [ 'iPhone', 'Samsung', 'Nokia', 'Sony' ] }, 
  { laptops: [ 'Mac', 'Dell', 'HP', 'Acer' ] } ]

My desired array would look like this

[ 'Ford', 'Chevy', 'Honda', 'Toyota','iPhone', 'Samsung', 'Nokia',
  'Sony','Mac', 'Dell', 'HP', 'Acer' ]

The way I'm trying to implement it, returns wrong result.

const arrayToPush = []
const getArrayEl = mappedProducts && mappedProducts.map(item => { 
for(let key in item){
    arrayToPush.push(item[key])
}
  return arrayToPush
})

Any help will be appreciated

const names = ["cars", "phones", "laptops"];

const nameArrayOfObj = [
  {
    cars: ["Ford", "Chevy", "Honda", "Toyota"],
  },
  {
    phones: ["iPhone", "Samsung", "Nokia", "Sony"],
  },
  {
    laptops: ["Mac", "Dell", "HP", "Acer"],
  },
];

const mappedProducts = names && nameArrayOfObj && names.map((_,i) => nameArrayOfObj[i]);

console.log("mappedProducts", mappedProducts);
const arrayToPush = []
const getArrayEl = mappedProducts && mappedProducts.map(item => { 
for(let key in item){
    arrayToPush.push(item[key])
}
  return arrayToPush
})
console.log("getArrayEl", getArrayEl);

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

0

You could use two .flatMap() calls, to loop through your array of product objects, and then an inner one to loop through your names from the products array. For each name, you can take the associated array from the object at that name:

const products = ["cars", "phones", "laptops"];
const productArrayOfObj = [ { cars: ["Ford", "Chevy", "Honda", "Toyota"], }, { phones: ["iPhone", "Samsung", "Nokia", "Sony"], }, { laptops: ["Mac", "Dell", "HP", "Acer"], }, ];

const res = productArrayOfObj.flatMap(obj => products.flatMap(
  name => obj[name] ?? []
));
console.log(res);

If your objects can only contain one key-array pair, then you can change your inner .flatMap() to a .find() to find the key being used in the object:

const products = ["cars", "phones", "laptops"];
const productArrayOfObj = [ { cars: ["Ford", "Chevy", "Honda", "Toyota"], }, { phones: ["iPhone", "Samsung", "Nokia", "Sony"], }, { laptops: ["Mac", "Dell", "HP", "Acer"], }, ];

const res = productArrayOfObj.flatMap(obj => {
  const key = products.find(name => obj.hasOwnProperty(name));
  return key ? obj[key] : [];
});
console.log(res);

about 4 years ago · Juan Pablo Isaza Relatório

0

Array.flatMap implementation.

Logic

  • Loop through names array with Array.flatMap.
  • Access each keys from nameArrayOfObj.

This implementation makes use of an asumprion that both arrays are in same order.

Working Fiddle

const names = ["cars", "phones", "laptops"];
const nameArrayOfObj = [
  { cars: ["Ford", "Chevy", "Honda", "Toyota"] },
  { phones: ["iPhone", "Samsung", "Nokia", "Sony"] },
  { laptops: ["Mac", "Dell", "HP", "Acer"] },
];
const mappedProducts = names.flatMap((name, i) => nameArrayOfObj[i][name] ? nameArrayOfObj[i][name] : []);
console.log(mappedProducts);

If you cannot ensure the arrays ae in same order, you can make use of this logic.

  • Loop through names Array.
  • Find an item from nameArrayOfObj array with the key in names Array.

Working Fiddle

const names = ["cars", "phones", "laptops"];
const nameArrayOfObj = [
  { cars: ["Ford", "Chevy", "Honda", "Toyota"] },
  { phones: ["iPhone", "Samsung", "Nokia", "Sony"] },
  { laptops: ["Mac", "Dell", "HP", "Acer"] },
];
const mappedProducts = names.flatMap((name, i) => {
  const matchingNode = nameArrayOfObj.find(item => item.hasOwnProperty(name));
  return matchingNode ? matchingNode[name] : [];
});
console.log(mappedProducts);

about 4 years ago · Juan Pablo Isaza Relatório

0

Is this your solution? Using the keys from products and flatMap()

const products = ["cars", "phones", "laptops"];

const productArrayOfObj = [
  {
    cars: ["Ford", "Chevy", "Honda", "Toyota"],
  },
  {
    phones: ["iPhone", "Samsung", "Nokia", "Sony"],
  },
  {
    laptops: ["Mac", "Dell", "HP", "Acer"],
  },
];

const mappedProducts= products.flatMap((_,i) => productArrayOfObj[i][_]);
console.log(mappedProducts)

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