Home > database >  How to insert each array item into each object of other array?
How to insert each array item into each object of other array?

Time:01-07

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)

CodePudding user response:

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);

CodePudding user response:

Your current functionality modifies the existing variable data. Try printing the data variable in the console to see what I mean.

CodePudding user response:

const qtyList = [1, 3, 2];


data = [{name: 'Sweater', qty: 1}, {name: 'Skirt', qty: 1}, {name: 'Socks', qty: 1}]



const updateQuantity = (list, data) => {
  if (data.length !== list.length) {
    return
  }


  for (let index = 0; index < list.length; index  ) {
    const element = list[index];

    // udpate data
    data[index] = {
      name: data[index].name,
      qty: element
    }
  }
 

  return data;

}


console.log(updateQuantity(qtyList, data));

CodePudding user response:

Use Spread syntax on item than change qty with array values

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]}
                ));

console.log("assignQty", assignQty );

CodePudding user response:

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)

CodePudding user response:

This is my approach to your question. In your example you were trying to map two arrays into one. This approach is "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)

  •  Tags:  
  • Related