如果数组元素有对象类型,我如何删除对象?



我有一个对象数据数组,在每个对象中我都有嵌套数组,在该数组中我需要删除对象,如果元素有一个数组。

输入数据:-

const data = [{"userDetails":[{"username":"Sai ","profileUrl":"","_id":4},{"username":"Mohamed Abu","profileUrl":"","_id":1},4,1]},{"userDetails":[{"username":"Sai ","profileUrl":"","_id":4},{"username":"Mohamed Abu","profileUrl":"","_id":1},4,1]},{"userDetails":[{"username":"Sai ","profileUrl":"","_id":4},4]},{"userDetails":[{"username":"Mohamed Abu","profileUrl":"","_id":1},1]}]

预期输出数据:-

data = [
{
userDetails: [4, 1],
},
{
userDetails: [4, 1],
},
{ 
userDetails: [4] 
},
{ 
userDetails: [1] 
},
];

请帮我解决这个问题。

提前感谢。

下面的代码片段应该可以完成这项工作。

data.map(x => removeNestedObj(x))

function removeNestedObj(x)
{
x.userDetails = x.userDetails.filter(y => Number.isInteger(y))
return x;
}

const data = [{"userDetails":[{"username":"Sai ","profileUrl":"","_id":4},{"username":"Mohamed Abu","profileUrl":"","_id":1},4,1]},{"userDetails":[{"username":"Sai ","profileUrl":"","_id":4},{"username":"Mohamed Abu","profileUrl":"","_id":1},4,1]},{"userDetails":[{"username":"Sai ","profileUrl":"","_id":4},4]},{"userDetails":[{"username":"Mohamed Abu","profileUrl":"","_id":1},1]}];
let finalData = data.map(a => a.userDetails)  //get userDetails array
.map(a => a.filter(x => typeof x !== 'object')) //remove objects from array
.map(a => {
return {userDetails: a} //recreate object with key userDetails
});

console.log(finalData);

您可以使用mapfilter,并与typeof进行比较,如下:

const data = [{
"userDetails": [{
"username": "Sai ",
"profileUrl": "",
"_id": 4
}, {
"username": "Mohamed Abu",
"profileUrl": "",
"_id": 1
}, 4, 1]
}, {
"userDetails": [{
"username": "Sai ",
"profileUrl": "",
"_id": 4
}, {
"username": "Mohamed Abu",
"profileUrl": "",
"_id": 1
}, 4, 1]
}, {
"userDetails": [{
"username": "Sai ",
"profileUrl": "",
"_id": 4
}, 4]
}, {
"userDetails": [{
"username": "Mohamed Abu",
"profileUrl": "",
"_id": 1
}, 1]
}]
// for removing object in userDetails
const result = data.map(obj => ({userDetails: obj.userDetails.filter(e => typeof e !== 'object')}))
console.log(result)
// for getting numbers in userDetails 
const result1 = data.map(obj => ({userDetails: obj.userDetails.filter(e => typeof e === 'number')}))
console.log(result1)

相关内容

  • 没有找到相关文章

最新更新