0

I was wondering if it is possible to destructure a nested object without knowing the key of the parent object?

The reason to do this is that mongoose validation errors returns an object in the errors key and each entry of this object is another object where the key is the name of the field that has an error.

const data = {
  name: {
    path: 'name',
    name: 'The error message'
  },
  email: {
    path: 'email',
    name: 'Another error message'
  }
}

So the result can be something like

{
  name: 'The error message',
  email: 'Another error message'
}

Is it possible that the unique way to do this is using for in loop and perform the destructuring assignment inside of it?

let message = {}
for (var k in data) {
  var { path, name } = data[k]
  message[path] = name
}
abaracedo
  • 1,404
  • 5
  • 26
  • 45

4 Answers4

1

You could take the values and map new objects. Then assign all objects to a single object.

const
    data = { name: { path: 'name', name: 'The error message' }, email: { path: 'email', name: 'Another error message' } }
    result = Object.assign({}, ...Object
        .values(data)
        .map(({ path, name }) => ({ [path]: name }))
    );

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Use Object.values like so:

const data = { name: { path: 'name', name: 'The error message' } };

const { path, name } = Object.values(data)[0];

console.log(path);
console.log(name);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

const data = {
  name: {
    path: 'name',
    name: 'The error message'
  }
}

const {path, name} = Object.values(data)[0];

console.log(path, name);
random
  • 7,756
  • 3
  • 19
  • 25
0

Yes you can do inside for in by taking the key and accessing the value and destructure it

const data = {
  name: {
    path: 'name',
    name: 'The error message'
  }
}

for(let key in data){
  let { path, name } = data[key]
  console.log('name --->',name)
  console.log('path --->',path)
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60