LoginSignup
0
0

More than 3 years have passed since last update.

オブジェクトの配列をflattenする

Last updated at Posted at 2021-03-31
//こういう配列を
var array = [{"hello":"aaa"},{"world":"bbb"},{"test":"ccc"},{"hoge":"ddd"}];

//こうしたい
console.log(flattened);
-> {hello: "aaa", world: "bbb", test: "ccc", hoge: "ddd"} 

reduceを使って簡易的に行うことができる。
(ただしこれだと、入れ子には対応できない)

const flattened = array.reduce((acc, val) =>{ 
    Object.keys(val).forEach(key => acc[key] = val[key]);
    return acc; 
}, {});

配列に同名のキーがある場合は上書きされるので注意

//同名のキーがある場合
var array = [{"hello":"aaa"},{"world":"bbb"},{"test":"ccc"},{"hoge":"ddd"}, {"world":123}];

//worldが上書きされてしまっている
console.log(flattened);
-> {hello: "aaa", world: 123, test: "ccc", hoge: "ddd"} 
0
0
2

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
0
0