【问题标题】:Convert array of object in the unique array转换唯一数组中的对象数组
【发布时间】:2023-02-09 22:48:30
【问题描述】:
我想将对象数组转换为属性中的唯一数组
谢谢!
收入数据
const food = [
{dinner: 'Apple', breakfest: 'Tomato'},
{dinner: 'Apple', breakfest: 'Apple'}
{dinner: 'Milk', breakfest: 'Banana'}
{dinner: 'Apple', breakfest: 'Milk'}
{dinner: 'Tomato', breakfest: 'Banana'}
]
收到
const whatIAmEat = ['Apple', 'Tomato', 'Milk', 'Banana']
我知道我可以在单独的变量中使用 ...new Set 而不是 concat() 来接收它,但它看起来很复杂。
【问题讨论】:
标签:
javascript
arrays
object
methods
javascript-objects
【解决方案1】:
也许创建一个空数组(此处:result),然后是loop over food,将dinner/breakfast值添加到result中(如果它们还不是included)。
const food=[{dinner:"Apple",breakfast:"Tomato"},{dinner:"Apple",breakfast:"Apple"},{dinner:"Milk",breakfast:"Banana"},{dinner:"Apple",breakfast:"Milk"},{dinner:"Tomato",breakfast:"Banana"}];
const result = [];
for (const { dinner, breakfast } of food) {
if (!result.includes(dinner)) result.push(dinner);
if (!result.includes(breakfast)) result.push(breakfast);
}
console.log(result);
附加文件
【解决方案2】:
另类
const food = [
{dinner: 'Apple', breakfast: 'Tomato'},
{dinner: 'Apple', breakfast: 'Apple'},
{dinner: 'Milk', breakfast: 'Banana'},
{dinner: 'Apple', breakfast: 'Milk'},
{dinner: 'Tomato', breakfast: 'Banana'}
]
const unique = {};
food.forEach(({dinner,breakfast}) => { unique[dinner] = true; unique[breakfast] = true; })
console.log(Object.keys(unique))
set还是比较简单的
const food = [
{dinner: 'Apple', breakfast: 'Tomato'},
{dinner: 'Apple', breakfast: 'Apple'},
{dinner: 'Milk', breakfast: 'Banana'},
{dinner: 'Apple', breakfast: 'Milk'},
{dinner: 'Tomato', breakfast: 'Banana'}
]
const unique = new Set();
food.forEach(({dinner,breakfast}) => { unique.add(dinner); unique.add(breakfast) })
console.log([...unique])