Extract objects from an object array to create a single object with all items

Asked

Viewed 437 times

0

Eae guys, I bugged here to solve a little problem. I have the following array:

[ 
  { cachorro: 'Bob', gato: 'Mica' },
  { dono: 'Jose', dona: 'Maria },
  { outros_animais: 'sim', animais: ['cavalo', 'vaca'] }
]

My goal is to create a single object with all these attributes, so the output looks like this:

{
  cachorro: 'Bob',
  gato: 'Mica',
  dono: 'Jose',
  dona: 'Maria,
  outros_animais: 'sim',
  animais: 
    ['cavalo', 'vaca']
}

I think I’m forgetting something, because it shouldn’t be too complicated but anyway, I bugged.

Thanks.

Edit: Actually, there’s a huge object and I don’t know the name of its attributes. So it has to be something generic.

2 answers

2


You can try it like this:

var source = [ 
  { cachorro: 'Bob', gato: 'Mica' },
  { dono: 'Jose', dona: 'Maria' },
  { outros_animais: 'sim', animais: ['cavalo', 'vaca'] }
];

var parsed = {};

source.forEach(function (item) {
	for (var i in item) {
		parsed[i] = item[i];
	}
});

console.log(parsed);

Note: If an array item contains a property name object that has already been used, it will be overwritten by its last occurrence in the source array.

  • Good brother, that’s right. Thanks

  • Nothing! Just don’t forget to accept the accepted answer.

  • I had to wait a minimum time, tai ja x)

1

Another option using Object.assign() and reduce():

let source = [
    { cachorro: 'Bob', gato: 'Mica' },
    { dono: 'Jose', dona: 'Maria' },
    { outros_animais: 'sim', animais: ['cavalo', 'vaca'] }
];

let result = source.reduce((acc, cur) => Object.assign(acc, cur));

console.log(result);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.