Search code examples
javascriptreactjsdictionaryarrow-functionsspread-syntax

Can anyone explain "items.map((item) =>item.id === id ? { ...item, checked: !item.checked } : item"?


Can anyone explain "items.map((item) =>item.id === id ? { ...item, checked: !item.checked } : item"? I just came up with this kind of example, don't know if it's correct.(if "onChange={() => Check(2)"} first loop:

    const listItems = items.map(({id: 1,checked: true,item: "Item 1"}) =>
      1 === 2 ? { {id: 1,checked: true,item: "Item 1"}, checked: !True } : "Item 1"
    );

second loop:

    const listItems = items.map(({id: 2,checked: true,item: "Item 2"}) =>
      2 === 2 ? { {id: 2,checked: false,item: "Item 2"}, checked: !false} : "Item 2"
    );

third loop:

    const listItems = items.map(({id: 3,checked: true,item: "Item 3"}) =>
      3 === 2 ? { {id: 3,checked: false,item: "Item 3"}, checked: !false} : "Item 3"
    );

Code:

const Content = () => {
  const [items, setItems] = useState([
    {
      id: 1,
      checked: true,
      item: "Item 1"
    },
    {
      id: 2,
      checked: false,
      item: "Item 2"
    },
    {
      id: 3,
      checked: false,
      item: "Item 3"
    }
  ]);

  const Check = (id) => {
    const listItems = items.map((item) =>
      item.id === id ? { ...item, checked: !item.checked } : item
    );
    setItems(listItems);
  };

  return (
    <main>
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            <input
              type="checkbox"
              onChange={() => Check(item.id)}
              checked={item.checked}
            />
            <label
              style={item.checked ? { textDecoration: "line-through" } : null}
              onDoubleClick={() => Check(item.id)}
            >
              {item.item}
            </label>
          </li>
        ))}
      </ul>
    </main>
  );
};

Solution

  • That's correct but you looping through all the object every time you can reduce the complexity by using find or findIndex (what find and find index do it will return immediately when the find first matching value) when you know the id and index number but that can be changed so I assume id will unique

    const Check = (givenId) => {
    let updatedUserList = [...items]
    const objIndex = updatedUserList.findIndex(user => user.id == givenId);
    updatedUserList[objIndex].checked = !updatedUserList[objIndex].checked;
    setItems(updatedUserList)
    }