我有一个使用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的值。
我应该循环通过响应并以这种方式执行,还是有更好的方式来映射?
答案 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