eozzy
eozzy

Reputation: 68670

Push to object instead of array

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 }

Upvotes: 0

Views: 70

Answers (1)

Will
Will

Reputation: 3241

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);

Upvotes: 4

Related Questions