Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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":"[email protected]",
   "address":"phill road",
   "salary":1222.00
},

 {
  "id":222,
  "date":"2020-08-03T08:00:00+00:00",
  "age":24,
   "email":"[email protected]",
   "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..

like image 796
user3643092 Avatar asked Oct 19 '25 02:10

user3643092


2 Answers

data=  [{
  "id":1111,
  "date":"2020-08-03T08:00:00+00:00",
  "age":23,
   "email":"[email protected]",
   "address":"phill road",
   "salary":1222.00
},
 {
  "id":222,
  "date":"2020-08-03T08:00:00+00:00",
  "age":24,
   "email":"[email protected]",
   "address":"phill2222 road",
   "salary":3344
},
 {
  "id":223,
  "date":"2020-08-03T08:00:00+00:00",
  "age":24,
   "email":"[email protected]",
   "address":"phill2222 road"
}
]

console.log(data.filter(e => e.salary).map(e => e.salary));
like image 67
Daniele Ricci Avatar answered Oct 21 '25 17:10

Daniele Ricci


data=  [{
  "id":1111,
  "date":"2020-08-03T08:00:00+00:00",
  "age":23,
   "email":"[email protected]",
   "address":"phill road",
   "salary":1222.00
},

 {
  "id":222,
  "date":"2020-08-03T08:00:00+00:00",
  "age":24,
   "email":"[email protected]",
   "address":"phill2222 road",
   "salary":3344
}]

console.log(data.map(item =>  item.salary))
like image 41
deepak Avatar answered Oct 21 '25 15:10

deepak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!