6

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.

3
  • Why not loop through the array and add the cssClass property the existing object? cssClasses.forEach(c => existing[c] = true) Commented Feb 23, 2024 at 14:26
  • use reduce to an object Commented Feb 23, 2024 at 14:26
  • Are you producing that array of objects solely to populate the starting object? Commented Feb 23, 2024 at 18:12

2 Answers 2

4

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

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

1 Comment

@derstauner Or result = Object.assign({}, originalObject, ...calcRowCssClasses) if leaving the original object alone is necessary.
2

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

1 Comment

Could also just add calcrow to the initial value provided to reduce and skip the destructuring entirely.

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.