2

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)

5 Answers 5

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

0

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)

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.