'Add new items to existing object model react js

junior trying to learn. I have the following function.

overlay = (rulersOnLine) => {
    const mainRulers = {
        AB: <Box sx={SX.ruler10} />,
        CD: <Box sx={SX.ruler20} />,
    };

    let skeleton;
    let newRulersOnLine = [];

    rulersOnLine.map((value, index) => {
        if (value === 1) {
            skeleton = {
                name: 'A' + index + 'B' + index,
                node: <Box sx={SX.ruler10} style={{opacity: 1}} />,
            };
        }
    });

    return mainRulers;
};

My main object is

const mainRulers = {
    AB: <Box sx={SX.ruler10} />,
    CD: <Box sx={SX.ruler20} />,
};

I want to add more items dynamic ex:

A1B1: <Box sx={SX.ruler20} />

rulersOnLine is an array made of 0,1 (max 4 elem).

How can I add new items (under the given form) to the main object?



Solution 1:[1]

If I understand correctly that you want to add it to mainRulers, You can do like

overlay = (rulersOnLine) => {
  const mainRulers = {
    AB: <Box sx={SX.ruler10} />,
    CD: <Box sx={SX.ruler20} />,
  };

  rulersOnLine.forEach((value, index) => {
    if (value === 1) {
      mainRulers[`A${index}B${index}`] = (
        <Box sx={SX.ruler10} style={{ opacity: 1 }} />
      );
    }
  });

  return mainRulers;
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siva K V