I am new to Javascript and I am stuck with this.
I have an array of objects
const items = [
{
product: 'prodOne',
quantity: 3,
sending: 100,
receiving: 50
},
{
product: 'prodTwo',
quantity: 4,
sending: 50,
receiving: 100
},
{
product: 'prodThree',
quantity: 8,
sending: 100,
receiving: 100
}
];
I am trying to change this array into an array of 2 key-value pairs, the new array would be something like this:
const itemsRed = [
{
product: 'prodOne',
quantity: 3,
},
{
product: 'prodTwo',
quantity: 4,
},
{
product: 'prodThree',
quantity: 8,
}
];
This is how I do it
const x = items.map(function (obj){
var prod = Object.values(obj)[0]
var qty = Object.values(obj)[1]
return {product: prod, quantity: qty}
})
The problem is that this depends on the index of the key-value pair [0] and if the positions are changed then it does not work. Is there a way to use the key instead of the index to get outcome.
const x = items.map(function (obj){
var prod = Object.values(obj)[0] //something like Object.values(obj['product']) which doesnt work
var qty = Object.values(obj)[1]
return {product: prod, quantity: qty}
})
Thanks.
>Solution :
You can make use of map, object destructuring as:
You have to create an object with 2 properties
productandquantity. So you can get it usingdotnotation or you can destructure it to get these 2 properties.
const x = items.map(function(obj) {
var prod = obj.product; // USE DOT NOTATION TO GET product
var qty = obj.quantity; // USE DOT NOTATION TO GET quantity
return {
product: prod,
quantity: qty
}
})
const items = [{
product: 'prodOne',
quantity: 3,
sending: 100,
receiving: 50
},
{
product: 'prodTwo',
quantity: 4,
sending: 50,
receiving: 100
},
{
product: 'prodThree',
quantity: 8,
sending: 100,
receiving: 100
}
];
const result = items.map(({ product, quantity }) => ({ product, quantity }));
console.log(result);
or
const items = [{
product: 'prodOne',
quantity: 3,
sending: 100,
receiving: 50
},
{
product: 'prodTwo',
quantity: 4,
sending: 50,
receiving: 100
},
{
product: 'prodThree',
quantity: 8,
sending: 100,
receiving: 100
}
];
const result = items.map((item) => ({
product: item.product,
quantity: item.quantity
}));
console.log(result);