Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

javascript - 将对象的对象转换为数组(特殊示例)(Transform an object of objects to an array (special example))

I am trying to transform an object of objects into an array of objects.(我正在尝试将对象的对象转换为对象的数组。)

Basically I want to transform this:(基本上,我想对此进行转换:) sales_over_time_week: { "1": { "orders": 96, "total": 270240 }, "2": { "orders": 31, "total": 74121 } } into this:(到这个:) [ {name: 1, orders:96, total:270240}, {name:2, orders:31, total: 74121} ] To just transform it normally I would do this(为了正常地转换它,我会这样做) var myData = Object.keys(items).map(key => { return items[key]; }); and it would give me(它会给我) [ {1: {orders: 31, total: 74121}}, {2: {orders: 52, total: 180284}} ] but my example is a bit special(但是我的例子有点特别)   ask by Besart Marku translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Object.entries with .map()(您可以将Object.entries.map())

let data = { "1": { "orders": 96, "total": 270240 }, "2": { "orders": 31, "total": 74121 } }; let result = Object.entries(data).map(([key, value]) => ({name: key, ...value})); console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...