Take the following array:
[
{
ndc: '0093415580',
name: 'Amoxicillin',
prescribing_physician: 'John Doe',
quantity: 150,
day_supply: 10,
pharmacy: 'Walmart',
source: 'Auto',
},
{
ndc: '499990882',
name: 'Lipitor',
prescribing_physician: 'John Doe',
quantity: 10,
day_supply: 30,
pharmacy: 'CVS Health',
source: 'Auto',
},
{
ndc: '5528947530',
name: 'Celebrix',
prescribing_physician: 'John Doe',
quantity: 25,
day_supply: 30,
pharmacy: 'CVS Health',
source: 'Manual',
},
];
How can I filter out all the name
and day_supply
and set them as key and values pairs into an array with objects like so?
myArr = [
{
name: 'Amoxicillin',
value: '10'
},
{
name: 'Lipitor',
value: '30'
},
{
name: 'Celebrix,
value: '30'
}
];
You can use Array.map
to process each object, returning only the name
and day_supply
(as value
) values:
const data = [{
ndc: '0093415580',
name: 'Amoxicillin',
prescribing_physician: 'John Doe',
quantity: 150,
day_supply: 10,
pharmacy: 'Walmart',
source: 'Auto',
},
{
ndc: '499990882',
name: 'Lipitor',
prescribing_physician: 'John Doe',
quantity: 10,
day_supply: 30,
pharmacy: 'CVS Health',
source: 'Auto',
},
{
ndc: '5528947530',
name: 'Celebrix',
prescribing_physician: 'John Doe',
quantity: 25,
day_supply: 30,
pharmacy: 'CVS Health',
source: 'Manual',
},
];
const myArr = data.map(({ name, day_supply }) => ({ name, value: day_supply }));
console.log(myArr);
const myObj = Object.fromEntries(data.map(({ name, day_supply }) => [name, day_supply]));
console.log(myObj);
Note that you may find an object with the name
values as properties to be more useful, the above snippet shows how to produce that using Object.fromEntries
.