简体   繁体   中英

How can i remove Objects if array elements has a object type?

I have array of objects data, in each object i have nested array, in that array i need to remove the object if element has a array.

Input Data :-

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]}]

Expected Output Data : -

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

Please help me in these issue.

Thanks in advance.

The following snippet should do the job.

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);

You can use map and filter and compare with typeof same as :

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM