0

I am trying to concat an array to an array (productsCategories) inside an array of objects.

So, here's what the productCategories array looks like:

[
  {
    id: 123,
    items: [ { Obj1 }, { Obj2 } ]
  },
  {
    id:456,
    items: [ { Obj1 }, { Obj2 } ]
  }
]

I have some new array, like [ { Obj3 }, { Obj4 } ] that I want to concat to the productCategories for the object where id = 123.

So to do this,

I've first used lodash's find to find the correct object to update and used concat to join the two arrays:

let nextItems:any = find(productCategories, { id: payload.id });
nextItems = assign({}, nextItems, { items: nextItems.items.concat(payload.items)});

So, nextItems.items has the concatenated items array.

However, I am having trouble now adding this to productCategories array. I need to find the object where id is the same as nextItems.id and then set productCategories.items equal to nextItems.items.

What is the correct way to do this?

2 Answers 2

2

Find the index of the object that matches the nextItems.id in the productCategories and assign the new concatenated array to it. You can use the lodash findIndex() method to find the index of the object that matches the id.

var index = _findIndex(productCategories, { id: nextItems.id });
productCategories[index].items = nextItems.items;
Sign up to request clarification or add additional context in comments.

Comments

1

You can use plain JavaScript just as well. With ES6 spread syntax it can look like this:

productCategories.filter(x => x.id == payload.id)
                 .forEach(x => x.items.push(...payload.items));

Here is a snippet with sample data:

// Sample data
var productCategories = [{
    id: 123,
    items: [ { a: 1 }, { a: 2 } ]
}, {
    id: 456,
    items: [ { b: 1 }, { b: 2 } ]
}];

var payload = {
    id: 123,
    items: [ { c: 1 }, { c: 2 } ]
};

// Update with payload
productCategories.filter(x => x.id == payload.id)
                 .forEach(x => x.items.push(...payload.items));

// Show results
console.log(productCategories);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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.