Array 中的对象,如何解决这个问题?

Objects inside Array, how to solve this problem?

My question is, how can i access each object inside an Array? or perhaps, how am I supposed to solve this problem? Like I know in head, i have to compare categories and then push into new const array that category. So far, i get each object in array wrote down, but I need to do an push method after category is same, and also after that to splice the category from each object.

My solution so far:

export const convert = inside => {
inside(({id,name,category}) => {
outside[category].push({id,name});
});
console.log(outside);
return outside;
}

抱歉,代码混乱,无法在此处加载。

您可以将 category 作为对象的键并推送一个新对象。

不需要每个类别的数组,因为此方法使用带有动态键的结果对象。

const
    inside = [{ id: 1, name: "orange", category: "fruits" }, { id: 2, name: "apple", category: "fruits" }, { id: 3, name: "carrot", category: "vegetable" }],
    outside = {};
    
inside.forEach(({ id, name, category }) => {
    outside[category] = outside[category] || [];
    outside[category].push({ id, name });
});

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

我不确定我是否理解这个问题,但从我认为需要的角度来看,您想从 outside 常量中获取所有项目并获取它们各自的 category,应用它到食物对象,然后将该对象添加到 inside 变量。

const outside = {
  fruits: [{
    id: 1,
    name: "orange"
  }, {
    id: 2,
    name: "apple"
  }],
  vegetable: [{
    id: 3,
    name: "carrot"
  }]
}
const categories = Object.keys(outside)

let inside = []

categories.forEach(category => {
  const categorizedFood = outside[category].map(f => ({...f, category }) )
  
  inside = [...inside, ...categorizedFood]
})

console.log(inside)
.as-console-wrapper {
  background: #FFF; 
  filter: invert(1) hue-rotate(210deg);
}