I have 2 arrays
I want this:
[{name: 'Sweater', qty: 1}, {name: 'Skirt', qty: 3}, {name: 'Socks', qty: 2}]
but I get
qtyList = [1, 3, 2]
data = [{name: 'Sweater', qty: 1}, {name: 'Skirt', qty: 1}, {name: 'Socks', qty: 1}]
let assignQty = data.map((x, id) => {
qtyList.map((y, idx) => {
if (idx == id) return x.qty = y
})
})
console.log('assignQty', assignQty)
You're essentially zipping the 2 lists together - typically done as follows:
const qtyList = [1, 3, 2]
const data = [{name: 'Sweater', qty: 1}, {name: 'Skirt', qty: 1}, {name: 'Socks', qty: 1}]
const result = data.map((item,idx) => ({...item, qty: qtyList[idx]}))
console.log(result);
Without using the spread operator, update the required field and then return x.
qtyList = [1, 3, 2]
data = [{name: 'Sweater', qty: 1}, {name: 'Skirt', qty: 1}, {name: 'Socks', qty: 1}]
var assignQty = data.map((x, id) => {x.qty=qtyList[id];return x;})
console.log('assignQty', assignQty)
This is my approach to your question. In your example, you were trying to map two arrays into one. This approach "loops" the data array containing the objects you want to change.
Using the index of each object it sets the item.qty to the value in qtyList[index].
qtyList = [1, 3, 2];
data = [{
name: 'Sweater',
qty: 1
}, {
name: 'Skirt',
qty: 1
}, {
name: 'Socks',
qty: 1
}];
let assignQty = data.map((item, index) => {
item.qty = qtyList[index];
return item;
});
console.log(assignQty)