skip to Main Content

I have this bit of code:

const calcRowCssClasses = (<string[]>context.dataItem.cssClasses).map(
        (cssClass) => {
          return { [cssClass]: true };
        }
      );

This produces the following array of objects:

{ "custom-calcrow-1": true },
{ "custom-calcrow-2": true }

Now, I have a starting object like this:

{ "calcrow": true}

The questin is, how can I add the above two entries to the existing object, such that the output will be an object like this:

{
  "calcrow": true,
  "custom-calcrow-1": true,
  "custom-calcrow-2": true
}

Basically, I would like to spread an array of objects. Doing like this

return { calcrow: true, ...calcRowCssClasses };

has this result:

0: {custom-calcrow-1: true},
1: {custom-calcrow-2: true},
calcrow: true

Which isn’t the expected result.

Thanks.

2

Answers


  1. Instead of .map() use Array.prototype.reduce

    const context = {dataItem: {cssClasses: ["custom-calcrow-1","custom-calcrow-2"]}};
    
    const calcRowCssClasses = context.dataItem.cssClasses.reduce((ob, cssClass) => (ob[cssClass] = true, ob), {});
    
    console.log({calcrow: true, ...calcRowCssClasses});
    Login or Signup to reply.
  2. You could take Object.assign with spreading the array as parameters.

    return Object.assign({ calcrow: true }, ...calcRowCssClasses);
    
    const calcRowCssClasses = [
        { "custom-calcrow-1": true },
        { "custom-calcrow-2": true }
    ];
    
    const originalObject = { calcrow: true };
    
    const result = Object.assign(originalObject, ...calcRowCssClasses);
    
    console.log(JSON.stringify(result, null, 4));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search