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

107
Vistas
Push data to right obect javascripts

i have function that return data like this :

test = [
    {test1:'test1'},
    {test2:'test2'}
]

results = [
   {id:1, name:'Leo'}
   {id:2, name : 'Max'}
] 

i have a funcion that i push data to results :

function addThisData(){
    const age = [{id:1, name:'14'},{id:2, name : '15'}]
    results.push(age)
}

it return like this :

results:[
   {id:1, name:'Leo'}
   {id:2, name : 'Max'}
   [{id:1, name:'Leo'},{id:2, name : 'Max'}]
}]

Any help to put the age in the object by id ? I want to achive this results:

{id:1,name:'leo',age:'14'}
{id:2,name:'Max',age:'15'}

Note i am learning this new


Is it possible to do it with foreach()

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Your result array should be array of objects, to do so


const results = [{
    0: { id: 1, name: 'Leo' },
    2: { id: 2, name: 'Max' }
}]


const age = [{ id: 1, name: '14' }, { id: 2, name: '15' }]

const newArr= []

//looping overelements of result to make a new array of objects
results.forEach((e) => {
    for (let key in e) {
        newArr.push(e[key])
    }
})
console.log(newArr);

const ages = [
    { id: 1, age: '14' },
    { id: 2, age: '15' }
]

// finding the equalIds by looping over on both array and assigned a new age property in new array with the help .map
let answer = []
for (let i = 0; i < ages.length; i++) {
    answer = newArr.map((elem) => {
        if (ages[i].id === elem.id) {
            elem.age = ages[i].age
        }
        return elem
    })
}

console.log(answer);
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use the find method (documentation here) to get the object you want and then updating the object.

Take care because the method will return null if there is no object corresponding to the parameters

So in your case you can use the for each method on one of the array (or any for loop you want like for i or for in) and update all value using find with the other array

It can be seen like

For each element on the age array, look for the element that match the id in the second array and add a property based on the value of this element


Example

const ages = [
    {id: 1, age: '14'},
    {id: 2,age: '15'}
  ]

const results = [
    {id: 1,name: 'Leo'},
    {id: 2,name: 'Max'}
  ]


//using foreach

ages.forEach((age) => {
  const resultAssociated = results.find(result => result.id === age.id)
  if (resultAssociated !== null) {
    age.name = resultAssociated.name
  }
})

console.log(ages)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use a map function. It works same like foreach but will help you to return a value at the end.

Go with the following code, you'll achieve what you need:

let test = [{id:1,name:'n1'}, {id:2,name:'n2'}];
let ages = [{id:1,age:12},{id:2,age:13}];

Imagine test and ages to be the default variables you're getting with the following values. For you to combine both and merge them into one array of objects you need to apply map and find functions.

result = test.map(ele => {
    let ageObject = ages.find(e => e.id === ele.id);    // #1
    return {...ele, ...ageObject};    // #2
});
console.log(result);   // array of objects with test and ages values merged

#1 .find() in this line works as a search function, it searches for the object over the given array of objects taking the condition given inside as the base. It returns the first found object with the matching condition in the given array and returns it.

#2 the "...ele" syntax is called the 'spread operator' syntax and it will spread all the elements inside the given object. {...ele} is equal to {id:1,name:'n1'}. This syntax helps in forming an object with the given elements while removing duplicates if any.

You can go with the traditional for loop inside for loop approach and compare each and every element manually and do the merging of objects but trying it this way will let you leverage the ES6 features.

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