admin管理员组

文章数量:1433480

I have array of objects data as below where ID is duplicate key in nested array of object:

 const arr =  [
      {
        "First Name": "ABC",
        "Last Name": "XYZ",
        "Gender": "MALE",
        "Id": "123",
        "moreDetails": {
          "items": [
            {
              "Id": "123",
              "City": "BLR",
              "State": "KA"
            }
          ]
        }
      },
      {
        "First Name": "Test",
        "Last Name": "Me",
        "Gender": "FEMALE",
        "Id": "12345",
        "moreDetails": {
          "items": [
            {
              "Id": "12345",
              "City": "KAN",
              "State": "UP"
            }
          ]
        }
      }
    ]

Expecting below format data where ID is now with one entry and nested array is also flattened:

[
  {
    "First Name": "ABC",
    "Last Name": "XYZ",
    "Gender": "MALE",
    "Id": "123",
    "City": "BLR",
    "State": "KA"
  },
  {
    "First Name": "Test",
    "Last Name": "Me",
    "Gender": "FEMALE",
    "Id": "12345",
    "City": "KAN",
    "State": "UP"
  }
]

I tried using Array.flat() and Array.flat(Infinity) but then do not work on this data set. I have also tried with simple for loop but not getting expected result. Can anyone please help with missing logic here.

const result2 = [];
for (let key in arr) {
if (arr.hasOwnProperty(key)) {
  if(!typeof arr[key].moreDetails === 'object'){
    result2.push(arr[key]);
  }else{
    for(let key2 in arr[key].moreDetails.items){
      result2.push(arr[key2]);
    }
  }
}
}

I have array of objects data as below where ID is duplicate key in nested array of object:

 const arr =  [
      {
        "First Name": "ABC",
        "Last Name": "XYZ",
        "Gender": "MALE",
        "Id": "123",
        "moreDetails": {
          "items": [
            {
              "Id": "123",
              "City": "BLR",
              "State": "KA"
            }
          ]
        }
      },
      {
        "First Name": "Test",
        "Last Name": "Me",
        "Gender": "FEMALE",
        "Id": "12345",
        "moreDetails": {
          "items": [
            {
              "Id": "12345",
              "City": "KAN",
              "State": "UP"
            }
          ]
        }
      }
    ]

Expecting below format data where ID is now with one entry and nested array is also flattened:

[
  {
    "First Name": "ABC",
    "Last Name": "XYZ",
    "Gender": "MALE",
    "Id": "123",
    "City": "BLR",
    "State": "KA"
  },
  {
    "First Name": "Test",
    "Last Name": "Me",
    "Gender": "FEMALE",
    "Id": "12345",
    "City": "KAN",
    "State": "UP"
  }
]

I tried using Array.flat() and Array.flat(Infinity) but then do not work on this data set. I have also tried with simple for loop but not getting expected result. Can anyone please help with missing logic here.

const result2 = [];
for (let key in arr) {
if (arr.hasOwnProperty(key)) {
  if(!typeof arr[key].moreDetails === 'object'){
    result2.push(arr[key]);
  }else{
    for(let key2 in arr[key].moreDetails.items){
      result2.push(arr[key2]);
    }
  }
}
}
Share Improve this question asked Nov 19, 2024 at 4:00 mkchoubemkchoube 1212 silver badges9 bronze badges 1
  • 1 Since items is an array, what's the output if it has 0 or more than 1 object in it? – Nick Parsons Commented Nov 19, 2024 at 5:26
Add a comment  | 

6 Answers 6

Reset to default 1

Iterate the array (arr) with Array.map(), destructure the object, and extract moreDetails. Use Object.assign() with array spread to merge the original object, and the items to a single object:

const arr = [{"First Name":"ABC","Last Name":"XYZ","Gender":"MALE","Id":"123","moreDetails":{"items":[{"Id":"123","City":"BLR","State":"KA"}]}},{"First Name":"Test","Last Name":"Me","Gender":"FEMALE","Id":"12345","moreDetails":{"items":[{"Id":"12345","City":"KAN","State":"UP"}]}}]

const result = arr.map(({ moreDetails, ...rest }) =>   
  Object.assign({}, rest, ...(moreDetails?.items ?? []))
)

console.log(result)

You can use Array#map with Array#reduce to merge such an object like so

const arr = [{
    "First Name": "ABC",
    "Last Name": "XYZ",
    "Gender": "MALE",
    "Id": "123",
    "moreDetails": {
      "items": [{
        "Id": "123",
        "City": "BLR",
        "State": "KA"
      }]
    }
  },
  {
    "First Name": "Test",
    "Last Name": "Me",
    "Gender": "FEMALE",
    "Id": "12345",
    "moreDetails": {
      "items": [{
        "Id": "12345",
        "City": "KAN",
        "State": "UP"
      }]
    }
  }
];

const flattened = arr.map(({ moreDetails, ...rest }) => ({
  ...rest,
  ...moreDetails?.items.reduce(Object.assign)
}));

console.log(flattened);

You can use map() to iterate over the array and extract the nested properties, then flatten the structure. Here's how you can transform the array to the desired format:

const arr = [
  {
    "First Name": "ABC",
    "Last Name": "XYZ",
    "Gender": "MALE",
    "Id": "123",
    "moreDetails": {
      "items": [
        {
          "Id": "123",
          "City": "BLR",
          "State": "KA"
        }
      ]
    }
  },
  {
    "First Name": "Test",
    "Last Name": "Me",
    "Gender": "FEMALE",
    "Id": "12345",
    "moreDetails": {
      "items": [
        {
          "Id": "12345",
          "City": "KAN",
          "State": "UP"
        }
      ]
    }
  }
];

const result = arr.map(item => {
  const details = item.moreDetails.items[0]; // Assuming there is always one item in the `items` array
  return {
    "First Name": item["First Name"],
    "Last Name": item["Last Name"],
    "Gender": item.Gender,
    "Id": item.Id,
    "City": details.City,
    "State": details.State
  };
});

console.log(result);
const arr = [
  {
    "First Name": "ABC",
    "Last Name": "XYZ",
    "Gender": "MALE",
    "Id": "123",
    "moreDetails": {
      "items": [
        {
          "Id": "123",
          "City": "BLR",
          "State": "KA"
        }
      ]
    }
  },
  {
    "First Name": "Test",
    "Last Name": "Me",
    "Gender": "FEMALE",
    "Id": "12345",
    "moreDetails": {
      "items": [
        {
          "Id": "12345",
          "City": "KAN",
          "State": "UP"
        }
      ]
    }
  }
];

const result = arr.map(item => {
  const details = item.moreDetails.items[0] || { City: null, State: null }; // Fallback if items array is empty
  return {
    "First Name": item["First Name"],
    "Last Name": item["Last Name"],
    "Gender": item.Gender,
    "Id": item.Id,
    "City": details.City,
    "State": details.State
  };
});

console.log(result);

     const arr =  [
          {
            "First Name": "ABC",
            "Last Name": "XYZ",
            "Gender": "MALE",
            "Id": "123",
            "moreDetails": {
              "items": [
                {
                  "Id": "123",
                  "City": "BLR",
                  "State": "KA"
                }
              ]
            }
          },
          {
            "First Name": "Test",
            "Last Name": "Me",
            "Gender": "FEMALE",
            "Id": "12345",
            "moreDetails": {
              "items": [
                {
                  "Id": "12345",
                  "City": "KAN",
                  "State": "UP"
                }
              ]
            }
          }
        ]
    
      const transformedArray = arr.map(item => {
          const moreDetails = item.moreDetails.items[0];
          return {
            ...item,
            ...moreDetails
          };
        });
        
    transformedArray.forEach(obj => delete obj.moreDetails);
    
    console.log(transformedArray);

You could take a cartesian product as flat result.

const
    getCartesian = object => Object.entries(object).reduce((r, [k, v]) => {
        const temp = [];
        r.forEach(s => (Array.isArray(v) ? v : [v])
            .forEach(w => w && typeof w === 'object'
                ? getCartesian(w).forEach(x => temp.push({ ...s, ...x }))
                : temp.push({ ...s, [k]: w })
            )
        );
        return temp;
    }, [{}]),
    data = [{ "First Name": "ABC", "Last Name": "XYZ", Gender: "MALE", Id: "123", moreDetails: { items: [{ Id: "123", City: "BLR", State: "KA" }, {x:'X' }] } }, { "First Name": "Test", "Last Name": "Me", Gender: "FEMALE", Id: "12345", moreDetails: { items: [{ Id: "12345", City: "KAN", State: "UP" }] } }],
    result = data.map(getCartesian).flat();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

本文标签: javascriptFlatten the array of objects and removing duplicate key entryStack Overflow