LoginSignup
2
1

More than 5 years have passed since last update.

配列の要素を正規化してオブジェクト化する

Posted at
const users = [
  {id: 1, name: 'Alice'}, 
  {id: 2, name: 'Bob'}, 
  {id: 3, name: 'Charlie'}
]

{
  1: {id: 1, text: 'Alice'}, 
  2: {id: 2, text: 'Bob'}, 
  3: {id: 3, text: 'Charlie'}
}

のようにidをキーにしたObjectに変換したい。

方法

import _ from 'lodash';

const users = [
  {id: 1, name: 'Alice'}, 
  {id: 2, name: 'Bob'}, 
  {id: 3, name: 'Charlie'}
]

const userObjects = _(users).map(x => [x.id, x]).fromPairs().value();
console.log(userObjects);

要素技術

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1