Home > Software engineering >  How can i remove Objects if array elements has a object type?
How can i remove Objects if array elements has a object type?

Time:07-15

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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)

  • Related