【问题标题】:return array of objects返回对象数组
【发布时间】:2023-02-10 16:04:30
【问题描述】:

我有解决方案,但是在 javascript 中还有其他更好的方法吗?或者是否可以修改 arr1 本身并将 arr1 单独作为对象数组

我有对象数组和字符串

arr1 = [{
    id: 'id1',
    name: 'name1'
}, {
    id: 'id2',
    name: 'name2'
}, '/roll', '/roll1'];

我想在最后单独拥有一组对象

newarr1 = [{
    id: "id1",
    name: "name1"
}, {
    id: "id2",
    name: "name2"
}]

当前解决方案

arr1.map((item) => {
    if (typeof item === 'object') return newarr1.push(item)
})

【问题讨论】:

  • 切勿在需要 forEach 的地方使用地图。 let newArr1 = []; arr1.forEach((item) => { if (typeof item === 'object') newarr1.push(item) })

标签: javascript arrays


【解决方案1】:
newArr = arr1.filter(item => typeof item === 'object')

【讨论】:

  • 不错的答案:) OP 的情况不需要这个,但有一点要知道:数组也被认为是对象,如果 OP 有嵌套数组并想要包含/排除它们,将对 Array.isArray(item) 进行额外检查帮助 :)
【解决方案2】:
const isObject = item => Object.getPrototypeOf(item) === Object.prototype;

const newarr1 = arr1.filter(isObject);

【讨论】:

    猜你喜欢
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 2016-08-28
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    相关资源
    最近更新 更多