Похоже, у вас первый элемент имеет тип массива:
container: (2) [{…}, {…}]
, а второй элемент - объект:
container: {user: null, id: 22, components: Array(1), currency: "EUR", total_price: 0.15, …}
Так вот почему он устанавливает егов массив.
Что вы можете сделать, это получить объект, а не массив для вашего первого элемента, и тогда ваш код будет работать. Позвольте мне показать пример:
const products = [
{
container : [{id: 1, currency: 'USD'}, {test: 'Hello, World:)'}],
id: 15,
markup_factor: "1.30",
name: "Sohil Test Product",
private: false,
profit_factor: "3.00",
recipe: {id: 1, user: null, ingredients: [], unit: "g", quantity: 4, },
sales_tax: "12.00",
tags: [{}],
total_price: 17.47,
user: 3
},
{
container : {id: 2, currency: 'Another Currency'},
id: 16,
markup_factor: "4.00",
name: "demo product 24",
private: false,
profit_factor: "4.00",
recipe: {id: 38, user: 3, ingredients: [], unit: "g", quantity: 0, },
sales_tax: "0.00",
tags: [],
total_price: "9.12",
user: 3,
},
{id: 21, user: 3, name: "DEMO PRODUCT", tags: [], sales_tax: "2.00", },
{id: 22, user: 3, name: "product 2", tags: [], sales_tax: "4.00", },
{id: 23, user: 3, name: "new product coming", tags: [], sales_tax: "3.00", },
{id: 24, user: 3, name: "new product", tags: [], sales_tax: "0.00", },
];
products.forEach((el, index) => {
let container = null;
let containerObj = null;
if (Array.isArray(el.container)
&& el.container.some(c=> c.currency && c.id)) {
container = el.container.find(c => c.currency && c.id);
containerObj = {
components: container,
currency: container.currency,
id: container.id,
name: null,
user: null
};
} else if(products[index].container && products[index].container.currency) {
containerObj = {
components: el,
currency: products[index].container.currency,
id: products[index].container.id,
name: null,
user: null
};
}
products[index].container = containerObj;
});
console.log(products)