skip to Main Content

i’m facing issue to convert object into array of object. i’m having object like,

const employeeDetails = {
  "admin-name": "deepak",
  "admin-age": "29",
  "tester-name": "raju",
  "tester-age": "26",
};

i’m expecting format like,

 const employeeDetails = [
  {
    _id: "admin",
    name: "deepak",
    age: 29,
  },
  {
   _id: "tester",
   name: "raju",
   age: 26,
  },
];

3

Answers


  1. const employeeDetails = {
      "admin-name": "deepak",
      "admin-age": "29",
      "tester-name": "raju",
      "tester-age": "26",
    };
    
    const resultObj = Object.entries(employeeDetails).reduce(
      (acc, [key, value]) => {
        const dashIndex = key.indexOf('-');
        const parts = [key.slice(0, dashIndex), key.slice(dashIndex+1)];
        
        acc[parts[0]] ??= { _id: parts[0] };
        acc[parts[0]][parts[1]] = value;
        return acc;
      }
    , {});
    
    const resultArr = Object.values(resultObj);
    
    console.log(resultArr);
    Login or Signup to reply.
  2. You can do:

    const employeeDetails = {
      "admin-name": "deepak",
      "admin-age": "29",
      "tester-name": "raju",
      "tester-age": "26",
    }
    
    const employeeArray = Object
      .entries(employeeDetails)
      .map(([key, value]) => {
        const [_id, attribute] = key.split('-')
        return {
          _id,
          [attribute]: value
        }
      })
      .reduce((acc, cur) => {
        acc[cur._id] ??= { _id: cur._id }
        Object.assign(acc[cur._id], cur)
        return acc
      }, {})
    
    const result = Object.values(employeeArray)
    console.log(result)
    Login or Signup to reply.
  3. const employeeDetails = {
      "admin-name": "deepak",
      "admin-age": "29",
      "tester-name": "raju",
      "tester-age": "26",
    }
    
    const restoreRecords = (from) => {
      const records = new Map();
      for (const [key, value] of Object.entries(from)) {
        const segmented = key.split("-");
        if (segmented.length === 2) {
          const record = records.get(segmented[0]);
          if (typeof record === "undefined") {
            const payload = {
              _id: segmented[0],
              [segmented[1]]: value,
            };
            records.set(payload._id, payload);
          } else {
            record[segmented[1]] = value;
          }
        }
      }
      return [...records.values()];
    };
    
    console.log(restoreRecords(employeeDetails));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search