I am trying to simplify an array with Javascript
[{
{name: orange,
quanity: 1},
{name: apple,
quanity: 3}
}]
I want
[{
orange:1,
apple: 3
}]
I have tried
const keys = flat.map(item => {
item.name = item.quanity
})
But I get
[ undefined, undefined ]
Thanks!
5
Answers
You can return the key-value pairs you want in the final object from the
map
callback, then useObject.fromEntries
to create the combined object.Similar, but slightly different solution, compared to the one from Unmigitiated. Both are nice and short.
Note : Input given in the question is not valid JavaScript syntax
The input given in the question is an array of objects, where each object represents a fruit and its corresponding quantity. To transform this input into the desired output, you can use the following code:
This code initializes an empty object ans and then iterates over each object in the input array using the forEach method. For each object, it extracts the name and quantity properties and adds them to the ans object as a key-value pair.
Here is another way, using
.reduce()
:Your input data structure is not valid. You need to remove the extra curly braces, and quote the string values (and maybe spell "quantity" correctly). So you’re left with:
There are a few ways to get the output you want but maybe the easiest is to use a
for..of
loop to iterate over the array. You can then use thename
andquantity
values to populate the property keys/values of an output object. If you want that object to be the only element in an array you can wrap the object later.Note: since we don’t know if the object names are unique I’ve added an additional object to the data so you can see how the addition works in this example.
Additional documentation
Destructuring assignment
Nullish coalescing assignment (
??=
)