1

I have an array object of variable length and i want to replace specific key elements of whole array with another array object which is also of variable length. I have tried different array methods but i am stuck at this one. I have 6 months of programming experience.

My code is:

a = [
 { id: 1, name: "Alex", qty: 6, prodCode: 1321 }, 
 { id: 2, name: "carry", qty: 2, prodCode: 1641 }, 
 { id: 1, name: "manuel", qty: 7, prodCode: 1754 },
.....]

b= [{qty:5},{qty:9},{qty:2},...]
a.length===b.length

Result should be like:

[
  { id: 1, name: "Alex", qty: 5, prodCode: 1321 }, 
  { id: 2, name: "carry", qty: 9, prodCode: 1641 }, 
  { id: 1, name: "manuel", qty: 2, prodCode: 1754 },
.....]
2
  • 1
    You say the arrays are of variable length, but can we assume a.length === b.length? Commented Jun 10, 2020 at 15:53
  • Yes a.length===b.length Commented Jun 10, 2020 at 16:17

2 Answers 2

3

If I understand it well, you can try this:

a.forEach((itemA, index) => {
    itemA.qty = b[index].qty
});

Hope it helps you.

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

Comments

0

For simplicity, this is what needs to be done

for( let index = 0; index < objectArray.length; index++ ){

   objectArray[index].qty = qtys[index].qty;

}

You can use the Browser's js console to understand where each value resides in a JSON Object and how to get a value from it.

For example, run this in the console after initializing the objectArray

objectArray[0].qty // This will give qty of the first object in the array

You can use this to navigate inside a complicated object

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.