英文:
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 => 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);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论