如何将data数组对象的score、title值分别推入对应数组
提取数组对象中的指定字段到新数组
问题说明
我有以下data数组对象,以及两个空数组scoreData和titleData:
scoreData = [] titleData = [] data = [ {score:1, title: 'tesh'}, {score:2, title: 'teshu'}, {score:3, title: 'teshiti'} ]
需要将data中每个对象的score值存入scoreData数组,title值存入titleData数组,最终得到:
scoreData = [1,2,3] titleData = ['tesh','teshu','teshiti']
注:原代码中
title的值未加引号,JavaScript中字符串需用引号包裹,否则会被识别为变量,示例中已补充引号修正。
解决方案
方法1:forEach遍历填充
直接遍历data数组,逐个将对应字段推入目标数组:
scoreData = [] titleData = [] data = [ {score:1, title: 'tesh'}, {score:2, title: 'teshu'}, {score:3, title: 'teshiti'} ] data.forEach(item => { scoreData.push(item.score) titleData.push(item.title) }) console.log(scoreData) // 输出:[1,2,3] console.log(titleData) // 输出:['tesh','teshu','teshiti']
方法2:map生成新数组
如果不需要保留原空数组的引用,用map可以直接生成目标数组,写法更简洁:
data = [ {score:1, title: 'tesh'}, {score:2, title: 'teshu'}, {score:3, title: 'teshiti'} ] const scoreData = data.map(item => item.score) const titleData = data.map(item => item.title) console.log(scoreData) // 输出:[1,2,3] console.log(titleData) // 输出:['tesh','teshu','teshiti']
方法3:单次遍历优化(适用于大数据量)
若数组元素较多,避免两次遍历的性能损耗,可通过一次循环同时填充两个数组:
scoreData = [] titleData = [] data = [ {score:1, title: 'tesh'}, {score:2, title: 'teshu'}, {score:3, title: 'teshiti'} ] for (const item of data) { scoreData.push(item.score) titleData.push(item.title) } console.log(scoreData) // 输出:[1,2,3] console.log(titleData) // 输出:['tesh','teshu','teshiti']
内容的提问来源于stack exchange,提问作者Teshie Ethiopia
相关产品推荐
相关产品推荐

