skip to Main Content

I know the title might be a bit confusing so I’ll try to explain visually. I’ve been struggling for days, I’ve searched all over but this is a very specific task.

I’m being provided with this API response:

{
   "akash": {
      "url": "127.0.0.1",
      "count": 12
   },
   "aptos": {
      "url": "127.0.0.2",
      "count": 54
   }
}

I need to convert it into a new object with this format:

{
   "akash": {
      "name": "akash",
      "url": "127.0.0.1",
      "count": 12
   },
   "aptos": {
      "name": "aptos",
      "url": "127.0.0.2",
      "count": 54
   }
}

If you can tell, now every subset has a new property "name" with the parent object’s key name as its value.

Another alternative would be to convert it into a proper array of objects, like this:

[
   {
      "name": "akash",
      "url": "127.0.0.1",
      "count": 12
   },
   {
      "name": "aptos",
      "url": "127.0.0.2",
      "count": 54
   }
]

2

Answers


  1. You can iterate through the keys of the object.

    Given you have an originalObject as your starting point, you can create a new object using the following code:

    const newObject = {};
    for (const key in originalObject) {
        if (originalObject.hasOwnProperty(key)) {
            const value = { ...originalObject[key], name: key };
            newObject[key] = value;
        }
    }
    

    To create a list, the process is quite similar, but you’re generating a new array of objects and pushing the new values to the list:

    const newList = [];
    for (const key in originalObject) {
        if (originalObject.hasOwnProperty(key)) {
            const value = { ...originalObject[key], name: key };
            newList.push(value);
        }
    }
    
    Login or Signup to reply.
  2. https://tsplay.dev/WPB8ZN

    type AddName<O, P = never> = {
      [K in keyof O | (P extends never ? never : 'name')]: K extends keyof O ?
      O[K] extends object ? AddName<O[K], K> : O[K]
      : P
    } & unknown
    
    function addName<O extends object, S>(o: O, name?: S): AddName<O, unknown extends S ? never : S> {
      if (name !== undefined) Object.assign(o, {name})
      for (let [k, v] of Object.entries(o)) {
        if (typeof o === 'object'&& o !== null) {
          addName(v, k)
        }
      }
      return o as any;
    }
    

    This does work recursively
    (note this adds name to existing objects, not creates new ones)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search