Search code examples
javascriptreactjsreact-nativeecmascript-6ecmascript-5

how to loop through nested objects and push fields after comparing them in javascript/es6


I have the following 3 items from the structure of data below:

how

  • Let's assume that group has three fields: id, name, accountNumber and because I have three items, two of them have the same accountNumber.

What i want to do

I want to write a function with javascript/es6 to loop through these objects, check the id and accountNumber in group and push that in a new array of objects named results. (If any id contains the same accountnumber it should not be pushed to the new array below)

# new array 
# results = [
{
    id: 1,
    accountNumber: 2289,
  },
  {
    id: 2,
    accountNumber: 9920,
  },
]

Because of my background with python i am struggling to accomplish this. any help would be very helpful.


Solution

  • Assuming all other data object properties are irrelevant, and I correctly represented your data (the image is cropped):

    const data = [
      {group: {id: 1, name:"name1", accountNumber: 1234}, plan:{}, plan_account:{}, plan_benefits:{}},
      {group: {id: 2, name:"name2", accountNumber: 1235}, plan:{}, plan_account:{}, plan_benefits:{}},
      {group: {id: 3, name:"name3", accountNumber: 1234}, plan:{}, plan_account:{}, plan_benefits:{}},
      {group: {id: 4, name:"name4", accountNumber: 1236}, plan:{}, plan_account:{}, plan_benefits:{}},
      {group: {id: 5, name:"name5", accountNumber: 1237}, plan:{}, plan_account:{}, plan_benefits:{}},
    ]
    
    const result = data.reduce((result, obj) => { 
        if(result.some(ele => ele.accountNumber === obj.group.accountNumber)) return result; 
        result.push({id: obj.group.id, accountNumber: obj.group.accountNumber});
        return result;
    }, []);
    
    //will filter out id 3 since it has same accountNumber as id 1
    console.log(result)