0

I'm using underscore to extract some props into a separate object but the structure is not as I want:

let element = {
    foo: 0,
    bar: 1,
    baz: _.map(
            _.filter(element.properties, (prop) => 
                _.contains(validationProps, prop.name)), (rule) => 
                    ({ [rule.name]: rule.value }) )
}

.. returns an array of objects for baz:

[ {"required":true} , {"maxLength":242} ]

.. what I need however is:

{ "required":true, "maxLength":242 }
2
  • What does element.properties look like? Plus, element still doesn't exist when u refer to itself from inside itself. element = {a: '1', foo: element.a} element.foo is undefined Commented Nov 16, 2018 at 5:03
  • @AbanaClara [{"name":"label","value":"Short 2"},{"name":"required","value":true},{"name":"maxLength","value":242}] Commented Nov 16, 2018 at 5:04

1 Answer 1

4

Or use JavaScript's Array.prototype.reduce()

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

let data = [{
    "name": "label",
    "value": "Short 2"
  },
  {
    "name": "required",
    "value": true
  },
  {
    "name": "maxLength",
    "value": 242
  }
];

let reformatted = data.reduce((pv, cv) => {
  pv[cv.name] = cv.value;
  return pv;
}, {});

console.log(reformatted);

Sign up to request clarification or add additional context in comments.

2 Comments

Incidentally, you can stick with underscore if you want. That has reduce as well.
Yep, thats what I went with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.