0

Despite the fact that the title seems difficult, let me give you a simple example. I have an object.

{
  name:"Ethan"
  pets:{cat:"joline",dog:"Momo",bird"Mimi"}
}

My goal is to push the values of the array to the object.

    {
      name:"Ethan",
      cat:"joline",
      dog:"Momo",
      bird"Mimi"
    }

The question is simple and I believe you can approach it in a clever way, thanks.

Ethanolle
  • 1,106
  • 1
  • 8
  • 26

4 Answers4

1

Simple way to do this is to combine pets object and other properties using spread operator and then delete the pets from result.

const data = {
  name:"Ethan",
  pets:{cat:"joline",dog:"Momo",bird:"Mimi"}
}

const res = {...data, ...data.pets};
delete res.pets;
console.log(res);

If you want to do it in a functional way you can use the following approach.

  • Wrap the original element in a array.
  • Apply map on it.
  • Destructure pets from the object and store the rest of the properties in other variable.
  • Return a new object where you spread the rest object and pets.

const data = {
  name:"Ethan",
  pets:{cat:"joline",dog:"Momo",bird:"Mimi"}
}

const res = [data].map(({pets, ...rest}) => ({...rest, ...pets}))[0]
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

Iterating through the elements and values in the object. And spreading the value into the return object

const data = {
  name: "Ethan",
  pets: {
    cat: "joline",
    dog: "Momo",
    bird: "Mimi"
  }
};

function flatten(data) {
  let result = {};

  for (const key in data) {
    const value = data[key];
    
    if (typeof value != 'object') result[key] = value;
    else result = { ...result, ... flatten(value)}
  }

  return result;
}

console.log(flatten(data));
a.mola
  • 3,883
  • 7
  • 23
0

The simplest and cleanest way to obtain desired result with destructuring.

const obj = {
  name: "Ethan",
  pets: { cat: "joline", dog: "Momo", bird: "Mimi" },
};

const { name, pets } = obj;
const result = { name, ...pets };
console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
0

As others have said, this is straightforward with object destructuring. I think it's cleanest when you use parameter destructuring. So a simple function like this should do it:

const promotePets = ({pets, ...rest}) => 
  ({...rest, ...pets})

const obj = {name: "Ethan", pets: { cat: "joline", dog: "Momo", bird: "Mimi" }};

console .log (promotePets (obj))
Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103