Barry D.
Barry D.

Reputation: 547

Mutating object in JavaScript

Helpful note: Consider reading the 'What's the purpose' part at the bottom, as I may not even have the best approach here, to begin with. Thanks.

Hey! So I've got this:

parent: {
    child1: {
        prop: 'hi there'
    },
    child2: {
        prop: 'hey there'
    }
}

I want to run some value-mapping magic to get it to be like this:

newObj: {
    child1: 'hi there',
    child2: 'hey there'
}

I want the mapping-function (or the correct name for this process) to essentially take the prop value of each child in parent, and set that value to the value part of a key that carries over the same name as on parent, if that makes sense.

Is the property on each child object always named prop?
Yes.

Why not define it that way from the start?
Because I've got other properties aside from prop that I need to use.

What's the purpose?
I'm using laravel. When I send this to the server for validation, I have to validate child1.prop rather than child1, which means the error messages send back as:

child1.prop : "Something is invalid"

... and I want it to be

child1:"Something is invalid"'

If there's a better way, please do suggest.

Upvotes: 0

Views: 64

Answers (1)

Mateus Junges
Mateus Junges

Reputation: 2602

Just adding the answer from @Chris G, so other users can find it easily:

const parent = {
  child1: {
    prop: 'hi there'
  },
  child2: {
    prop: 'hey there'
  }
};

const newObj = Object.entries(parent).reduce((a, [key, { prop }]) => ({ ...a, [key]: prop }), {});

out.textContent = JSON.stringify(newObj);

Upvotes: 1

Related Questions