如何按键过滤数组并使用javascript将值推送到另一个数组

Posted

技术标签:

【中文标题】如何按键过滤数组并使用javascript将值推送到另一个数组【英文标题】:How to filter an array by key and push the value to another array using javascript 【发布时间】:2020-11-25 20:06:03 【问题描述】:

这是我的第一个数组

data=  [
  "id":1111,
  "date":"2020-08-03T08:00:00+00:00",
  "age":23,
   "email":"test@yahoo.com",
   "address":"phill road",
   "salary":1222.00
,

 
  "id":222,
  "date":"2020-08-03T08:00:00+00:00",
  "age":24,
   "email":"tes22t@yahoo.com",
   "address":"phill2222 road",
   "salary":3344

]

第二个数组应该是这样的

  dataNew=  [1222.00,3344]

我需要第二个仅包含 工资值 的数组。如何过滤第一个数组,如果 keys name = "salary" ,将值推送到新数组。搜索了这么多建议,但似乎没有什么对我有用..

【问题讨论】:

【参考方案1】:

data=  [
  "id":1111,
  "date":"2020-08-03T08:00:00+00:00",
  "age":23,
   "email":"test@yahoo.com",
   "address":"phill road",
   "salary":1222.00
,
 
  "id":222,
  "date":"2020-08-03T08:00:00+00:00",
  "age":24,
   "email":"tes22t@yahoo.com",
   "address":"phill2222 road",
   "salary":3344
,
 
  "id":223,
  "date":"2020-08-03T08:00:00+00:00",
  "age":24,
   "email":"tes22t@yahoo.com",
   "address":"phill2222 road"

]

console.log(data.filter(e => e.salary).map(e => e.salary));

【讨论】:

【参考方案2】:
data=  [
  "id":1111,
  "date":"2020-08-03T08:00:00+00:00",
  "age":23,
   "email":"test@yahoo.com",
   "address":"phill road",
   "salary":1222.00
,

 
  "id":222,
  "date":"2020-08-03T08:00:00+00:00",
  "age":24,
   "email":"tes22t@yahoo.com",
   "address":"phill2222 road",
   "salary":3344

]
const dataNew=[]
data.map(item=>item.salary?dataNew.push(item.salary):null)

【讨论】:

【参考方案3】:

这个

data = [
    "id": 1111,
    "date": "2020-08-03T08:00:00+00:00",
    "age": 23,
    "email": "test@yahoo.com",
    "address": "phill road",
    "salary": 1222.00
  ,

  
    "id": 222,
    "date": "2020-08-03T08:00:00+00:00",
    "age": 24,
    "email": "tes22t@yahoo.com",
    "address": "phill2222 road",
    "salary": 3344
  
]
arr = []
for (i = 0; i < data.length; i++) 
  console.log(data[i]['salary'])
  arr.push(data[i]['salary']);

console.log(arr)

【讨论】:

【参考方案4】:

你可以在数组上使用.map()

data.map(item => item.salary)

【讨论】:

【参考方案5】:

data=  [
  "id":1111,
  "date":"2020-08-03T08:00:00+00:00",
  "age":23,
   "email":"test@yahoo.com",
   "address":"phill road",
   "salary":1222.00
,

 
  "id":222,
  "date":"2020-08-03T08:00:00+00:00",
  "age":24,
   "email":"tes22t@yahoo.com",
   "address":"phill2222 road",
   "salary":3344
]

data.map(item =>  item.salary)

【讨论】:

以上是关于如何按键过滤数组并使用javascript将值推送到另一个数组的主要内容,如果未能解决你的问题,请参考以下文章

如何在多维数组中推送值

通过按键过滤数组,使用 jq 展平 JSON 文档

如何一次将一个项目添加(推送)到一个数组(循环遍历数组)

使用Javascript比较(过滤)动态数组中的多个数组值

拆分最后两个单词并在javascript中过滤

如何在javascript对象中按键查找对象?