返回对象数组

huangapple go评论63阅读模式
英文:

return array of objects

问题

I have the solution but Is there any other nicer way to do in javascript or is it possible to modify the arr1 itself and have arr1 as array of objects alone

我有解决方案,但是否有更好的JavaScript方法,或者是否可能修改arr1本身,使arr1仅为对象数组

I have array of objects and string

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

我有对象数组和字符串

I would like to have array of objects alone at the end

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

我希望最后只有对象数组

Current solution

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

当前的解决方案

英文:

I have the solution but Is there any other nicer way to do in javascript or is it possible to modify the arr1 itself and have arr1 as array of objects alone

I have array of objects and string

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

i would like to have array of objects alone at the end

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

current solution

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

答案1

得分: 4

newArr = arr1.filter(item => typeof item === 'object')

英文:
newArr = arr1.filter(item => typeof item === 'object')

答案2

得分: 3

const isObject = item => Object.getPrototypeOf(item) === Object.prototype;

const newarr1 = arr1.filter(isObject);
const isObject = item => Object.getPrototypeOf(item) === Object.prototype;
const arr1 = [{id: 'id1', name: 'name1'}, {id: 'id2', name: 'name2'}, '/roll', '/roll1'];
const newarr1 = arr1.filter(isObject);
console.log(newarr1);
英文:
const isObject = item => Object.getPrototypeOf(item) === Object.prototype;

const newarr1 = arr1.filter(isObject);

Demo

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const isObject = item =&gt; Object.getPrototypeOf(item) === Object.prototype;

const arr1 = [{id: &#39;id1&#39;, name: &#39;name1&#39;}, {id: &#39;id2&#39;, name: &#39;name2&#39;}, &#39;/roll&#39;, &#39;/roll1&#39;];
const newarr1 = arr1.filter(isObject);

console.log(newarr1);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月10日 15:54:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定