1

I have the following structure

[
  { type: 'total_users', total: '393647' },
  { type: 'total_male_users', total: '259555' },
  { type: 'total_female_users', total: '134092' },
  { type: 'active_users', total: '1232' },
  { type: 'active_male_users', total: '144' }
]

I'm trying to convert this into an object (something like the following)... I would like to reference the object like "blah.total_users"

{
  'total_users': '393647',
  'total_male_users',
  'total_female_users',
  'active_users',
  'active_male_users'
}

Being trying the following but I'm a way off - returns an array and errors with the return structure below.

statistics = statisticsResult.rows.map((data) => [data.type]: data.total)

thankyou

1
  • 1
    map will return another array.. if you want to change array to object, you can do it using reduce function (instead of map function) Commented Mar 24, 2021 at 21:57

2 Answers 2

2

You can use arr.reduce (instead of arr.map, because map will return an array) to do this, for ex:

const arr = [
  { type: 'total_users', total: '393647' },
  { type: 'total_male_users', total: '259555' },
  { type: 'total_female_users', total: '134092' },
  { type: 'active_users', total: '1232' },
  { type: 'active_male_users', total: '144' }
];

const x = arr.reduce((acc, cur) => {
  acc[cur.type] = cur.total;
  return acc;
}, {});

console.log(x);
Sign up to request clarification or add additional context in comments.

Comments

1

The easiest way is with lodash, using assign() or defaults().

Which you use is dependent on the behavior you want.

const _ = require('lodash');
[
  { type: 'total_users', total: '393647' },
  { type: 'total_male_users', total: '259555' },
  { type: 'total_female_users', total: '134092' },
  { type: 'active_users', total: '1232' },
  { type: 'active_male_users', total: '144' }
];

const obj = _.assign( {}, ...arr );

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.