简体   繁体   中英

How to filter an array by key and push the value to another array using javascript

this is my first array

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
}
]

second array should look like this

  dataNew=  [1222.00,3344]

I need second array that only contain the salary value . How can I filter the first array, that if the keys name = "salary", push the value to new array. Searched for so many suggestion, but nothing seems working for me..

 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));

 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)

You can use .map() on the array

data.map(item => item.salary)

This

 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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM