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

问题描述 投票:2回答:2

我的问题是,如何访问数组中的每个对象?或者,我怎么能解决这个问题呢?就像我在头脑中所知,我必须比较类别,然后推入新的const数组类别。到目前为止,我得到数组中的每个对象写下来,但我需要在类别相同之后执行推送方法,并且之后还要从每个对象拼接类别。

到目前为止我的解

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

对不起乱码,无法载入此处。

javascript object arr
2个回答
1
投票

您可以将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; }

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.