-
富国沪深
var data = { "audioResponse": [{ "speaker": "spk1", "startTime": "0.0", "endTime": "15.239", "emotion": "neutral", "emotionScore": "0" }, { "speaker": "silence", "startTime": "15.240", "endTime": "16.900", "emotion": "NA", "emotionScore": "NA" }, { "speaker": "spk2", "startTime": "16.932", "endTime": "27.320", "emotion": "happy", "emotionScore": "2" }, { "speaker": "spk1", "startTime": "27.977", "endTime": "37.900", "emotion": "anger", "emotionScore": "-3" }]};var result = { audioResponse: []};for (var item of data.audioResponse) { var existed = result.audioResponse.find(x => x[item.speaker]); if (!existed) result.audioResponse.push({ [item.speaker]: [] }); existedArray = result.audioResponse.find(x => x[item.speaker])[item.speaker]; var copy = {...item}; delete copy.speaker; existedArray.push(copy);}console.log(result);
-
慕雪6442864
var inputList = { "audioResponse": [ { "speaker":"spk1", "startTime": "0.0", "endTime": "15.239", "emotion": "neutral", "emotionScore": "0" }, { "speaker":"silence", "startTime": "15.240", "endTime": "16.900", "emotion": "NA", "emotionScore": "NA" }, { "speaker":"spk2", "startTime": "16.932", "endTime": "27.320", "emotion": "happy", "emotionScore": "2" }, { "speaker":"spk1", "startTime": "27.977", "endTime": "37.900", "emotion": "anger", "emotionScore": "-3" } ]}var result = inputList.audioResponse.reduce((acc, {speaker, ...rest})=>{ acc['audioResponse'][speaker] = (acc['audioResponse'][speaker]) || []; acc['audioResponse'][speaker].push(rest); return acc;}, {audioResponse:{}});console.log(result);
-
长风秋雁
但我想将其更改为需要拾取其中一个嵌套值并将其投影为上级键的格式您可以将组形成的属性设置为动态'use strict';let attribute = 'speaker'; // can be 'speaker' or 'emotion' or 'emotionScore'let output = { audioResponse: []};for (let response of data.audioResponse) { let groupKey = response[attribute]; let group = output.audioResponse[groupKey]; delete response[attribute]; //remove the key if (group) { group.push(response); } else { group = [response]; } output.audioResponse[groupKey] = group;}console.log(output);