如何创建每个对象的财产的阵列? [重复]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何创建每个对象的财产的阵列? [重复]相关的知识,希望对你有一定的参考价值。
这个问题已经在这里有一个答案:
我找到了多个类似的问题,但不能得到如何做到以下几点:
我得到这个类型从服务器的数据:
test_data =
'222':
joy: 66.5057373046875,
fear: 1.0003513832343742,
anger: 2.000018799044483,
disgust: 3.004251452162862,
sadness: 4.0001135088386945,
contempt: 5.001299204188399,
surprise: 6.203749045729637
,
'238':
joy: 97.06363677978516,
fear: 17.500137131541123,
anger: 27.00000593749519,
disgust: 6.001324078417383,
sadness: 21.000043172625737,
contempt: 21.00033742573578,
surprise: 32.62530106306076
,
'722':
joy: 66.5057373046875,
fear: 60.000351383234374,
anger: 70.00001879904448,
disgust: 10.004251452162862,
sadness: 92.0001135088387,
contempt: 40.0012992041884,
surprise: 50.20374904572964
我需要的是创建用于test_data
对象内的每个对象的阵列,例如,joyArray
容纳所有joy
值,fearArray
所有fear
值等。实施例:
joyArray = [66.5057373046875, 97.06363677978516, 66.5057373046875]
我不知道如何做到这一点,我试图玩弄Object.keys
,但没能做到这一点。有什么建议?
答案
最简单的方法是,大概是:
let test_data =
'222':
joy: 66.5057373046875,
fear: 1.0003513832343742,
anger: 2.000018799044483,
disgust: 3.004251452162862,
sadness: 4.0001135088386945,
contempt: 5.001299204188399,
surprise: 6.203749045729637
,
'238':
joy: 97.06363677978516,
fear: 17.500137131541123,
anger: 27.00000593749519,
disgust: 6.001324078417383,
sadness: 21.000043172625737,
contempt: 21.00033742573578,
surprise: 32.62530106306076
,
'722':
joy: 66.5057373046875,
fear: 60.000351383234374,
anger: 70.00001879904448,
disgust: 10.004251452162862,
sadness: 92.0001135088387,
contempt: 40.0012992041884,
surprise: 50.20374904572964
,
// we retrieve an Array of the nested Objects
// (the Object-values) using Object.values(), and
// and then use Array.prototype.map() to iterate
// over that Array of values:
joyArray = Object.values(test_data).map(
// here we pass the current Object-value into
// the Arrow function (emotionsObject is reference
// to that current Object; here we (implicitly)
// return the value held in the 'joy' property:
(emotionsObject) => emotionsObject.joy
);
console.log(joyArray);
另一答案
您可以使用reduce
,Object.values
和Object.entries
是这样的:
const test_data = '222':joy:66.5057373046875,fear:1.0003513832343742,anger:2.000018799044483,disgust:3.004251452162862,sadness:4.0001135088386945,contempt:5.001299204188399,surprise:6.203749045729637,'238':joy:97.06363677978516,fear:17.500137131541123,anger:27.00000593749519,disgust:6.001324078417383,sadness:21.000043172625737,contempt:21.00033742573578,surprise:32.62530106306076,'722':joy:66.5057373046875,fear:60.000351383234374,anger:70.00001879904448,disgust:10.004251452162862,sadness:92.0001135088387,contempt:40.0012992041884,surprise:50.20374904572964
const output = Object.values(test_data).reduce((r, v) =>
Object.entries(v).forEach(([k, v]) => (r[k] = r[k] || []).push(v))
return r;
, )
console.log(output)
以上是关于如何创建每个对象的财产的阵列? [重复]的主要内容,如果未能解决你的问题,请参考以下文章