javascript 使用es6Map创建一个包含空对象的对象

ecbunoof  于 2022-12-02  发布在  Java
关注(0)|答案(1)|浏览(146)

I searched a while but couldn't find the answer that I want. I am have a very simple question, how to get rid of the empty objects from Map.

const friuts = [{
    apple: 'red',
    banana: 1
  },
  {
    apple: 'green',
    banana: 1
  },
  {
    apple: 'yellow',
    banana: 3
  }
]

const newObject = friuts.map(e =>
  ({ ...e.banana === 1 ? {
      apple: e.apple
    } :
      []
  })
)

console.log(newObject)

If you check the console.log it contains an empty object at the end

[
  {
    "apple": "red"
  },
  {
    "apple": "green"
  },
  {} <--- empty 
]

Also I tried undefined or below code, but just can't get rid of the empty objects.

...e.banana === 1 &&
    {
        apple: e.apple
    }

I understand this can be easily done by using other methods like filter . However, I am learning Map , so I'd like to learn how to get rid of the empty objects from map.
Sorry for if the question has been asked before. I will remove the question if it is duplicated.

k5ifujac

k5ifujac1#

要从结果数组中删除空对象,可以使用filter方法将它们从最终数组中排除。可以使用Object.keys方法检查对象是否为空。下面是一个示例:

const fruits = [{
    apple: 'red',
    banana: 1
  },
  {
    apple: 'green',
    banana: 1
  },
  {
    apple: 'yellow',
    banana: 3
  }
];

const newObject = fruits
  .map(e => ({ ...e.banana === 1 ? { apple: e.apple } : {} }))
  .filter(e => Object.keys(e).length > 0);

console.log(newObject);

在上面的代码中,map方法用于为具有值为1的banana属性的对象创建一个仅包含apple属性的新数组。生成的数组可能包含空对象,因此使用filter方法将它们从最终数组中排除。
注意,我还从map方法的对象spread语法中删除了方括号,以避免创建对象数组。相反,使用spread操作符创建了一个新对象,该对象将包含在结果数组中。

相关问题