Javascript JSON - 将项目转换为新数组

时间:2018-06-07 09:09:44

标签: javascript arrays json

我有一个使用stringify转换的javascript对象,看起来像这样..

var myJSON = JSON.stringify(response);

{"0":{"trigger":17},"1":{"trigger":3},"2":{"trigger":40},"3":{"trigger":4},"4":{"trigger":19},"5":{"trigger":70},"6":{"trigger":80},"7":{"trigger":0},"8":{"trigger":0},"9":{"trigger":5},"10":{"trigger":4}}

我正在尝试创建一个数组但只包含trigger的值。

我应该循环通过响应并以这种方式执行,还是有更好的方式来映射?

3 个答案:

答案 0 :(得分:5)

您可以在map上使用Object.values方法。



const json = {"0":{"trigger":17},"1":{"trigger":3},"2":{"trigger":40},"3":{"trigger":4},"4":{"trigger":19},"5":{"trigger":70},"6":{"trigger":80},"7":{"trigger":0},"8":{"trigger":0},"9":{"trigger":5},"10":{"trigger":4}}

const arr = Object.values(json).map(({trigger}) => trigger);
console.log(arr)




答案 1 :(得分:3)

您可以使用Object.values从对象获取所有值,然后对集合应用Array.map以仅获取trigger的值:

const obj = {"0":{"trigger":17},"1":{"trigger":3},"2":{"trigger":40},"3":{"trigger":4},"4":{"trigger":19},"5":{"trigger":70},"6":{"trigger":80},"7":{"trigger":0},"8":{"trigger":0},"9":{"trigger":5},"10":{"trigger":4}};

const arr = Object.values(obj).map(item => item.trigger);
console.log(arr);

答案 2 :(得分:2)

使用class迭代对象并将值推送到NSNumber到另一个数组



for..in