skip to Main Content

Is it possible to flatten or remove the topmost key of an object? For example:

const obj = {
  page: {
    title: 'x',
    images: {
      0: {
        src: '...'
      }
    }
  }
}

So I can get:

{
  title: 'x',
  images: {
    0: {
      src: '...'
    }
  }
}

I tried with map but the result isn’t what I am looking for:

const x = Object.keys(obj).map((key)=>{
  return obj[key]
})

Any ideas?

4

Answers


  1. You could take the values and assign to a new object.

    result = Object.assign({}, ...Object.values(data));
    
    Login or Signup to reply.
  2. You can simply achieve this by iterating the object keys.

    Try this :

    let obj = {
      page: {
        title: 'x',
        images: {
          0: {
            src: '...'
          }
        }
      }
    };
    
    Object.keys(obj).forEach(key => obj = (typeof obj[key] === 'object') ? obj[key] : obj)
    
    console.log(obj);
    Login or Signup to reply.
  3. You can try this ..

    const obj = {
      page: {
        title: 'x',
        images: {
          0: {
            src: '...'
          }
        }
      }
    };
    
    const {
      page,
      ...flattenedObj
    } = obj;
    
    console.log(flattenedObj);

    This uses object destructuring to create a new object (flattenedObj) without the ‘page’ key. The original object obj remains unchanged. The resulting flattenedObj will have the structure you’re looking for:

    {
      title: 'x',
      images: {
        0: {
          src: '...'
        }
      }
    }
    
    Login or Signup to reply.
  4. All current answers create a new object. This one will modify the existing one

    const data = {
      page: {
        title: 'x',
        images: {
          0: {
            src: '...'
          }
        }
      }
    }
    
    function flatten(obj) {
      let [k,v] = Object.entries(obj)[0];
      delete obj[k]
      
      Object.assign(obj, v);
    }
    
    flatten(data);
    console.log(data);

    If assigning to another object is also ok, this simple approach will work too.

    const data = {
      page: {
        title: 'x',
        images: {
          0: {
            src: '...'
          }
        }
      }
    }
    
    const flat = Object.values(data)[0];
    console.log(flat)

    Be aware, that neither of these approaches deepclones you data. And they both assume the structure of the original data is ok (ie it’s an object with a single property at top level. And that property’s value is a valid object itself)

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