0

lets say I have an array like this:

[ { full_name: 'Sickö' }, 
  { location: 'New York City, United States' },
  { follower: '1.2M' },
  { er: '5.59%' },
  { topics: 'Fashion' } ]

and I want to make it as an object like:

{
  fullname: 'Sicko',
  location: 'New York City, United State'
  ..and more
}

I'm aware that I can combine them using Object.assign but no idea how I can assign all of them.

1
  • How do you know when to move onto another object as the array in your example appears have an object designated for each property of the object you want to create. Commented Jul 2, 2019 at 21:22

3 Answers 3

4
let all = [ { full_name: 'Sickö' }, 
  { location: 'New York City, United States' },
  { follower: '1.2M' },
  { er: '5.59%' },
  { topics: 'Fashion' } ];

let res = Object.assign({}, ...all);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Array.reduce() starting with an accumulator equal to the empty object {} and use Object.assign() on each iteration of the reducer. Something like this:

const input = [
  {full_name: 'Sickö'},
  {location: 'New York City, United States'},
  {follower: '1.2M'},
  {er: '5.59%'},
  {topics: 'Fashion'}
];

function assign(acc, obj)
{
    return Object.assign(acc, obj);
}

let res = input.reduce(assign, {});
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

However, Object.assign() is designed to accept multiple sources, so you can just use it with the spread syntax if you have ES6 support:

const input = [
  {full_name: 'Sickö'},
  {location: 'New York City, United States'},
  {follower: '1.2M'},
  {er: '5.59%'},
  {topics: 'Fashion'}
];

let res = Object.assign({}, ...input);
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

1 Comment

How does this work when their are multiple objects in the array ie, not every single object is to be part of one single object?
0

As you tagged jquery, incase you need a solution using the same:

var data = [ { full_name: 'Sickö' }, 
  { location: 'New York City, United States' },
  { follower: '1.2M' },
  { er: '5.59%' },
  { topics: 'Fashion' } ];

var d = $.extend({}, ...data);

console.log(d);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.