简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM