首页 > 解决方案 > 无法根据 id 更改项目,预期结果应该是输出格式,它应该返回正确的值和更新的值

问题描述

无法根据 id 更改项目,预期结果应为输出格式

const items = [
        { id: 1, value: "first" },
        { id: 2, value: "second" },
        { id: 3, value: "third" }
      ];
      const expectedOutput = [
{ id: 1, value: "first" },
        { id: 2, value: "newvalue" },
        { id: 3, value: "third" }
]
      function getData(value, id) {
       return items.map((_each)=> {
         if(_each.id === id) {
           //need to update items with id=2
         }
       })
      }
      
      console.log(getData("newvalue", 2))

标签: javascript

解决方案


const items = [
        { id: 1, value: "first" },
        { id: 2, value: "second" },
        { id: 3, value: "third" }
      ];
      const expectedOutput = [
{ id: 1, value: "first" },
        { id: 2, value: "newvalue" },
        { id: 3, value: "third" }
]
      function getData(value, id) {
       return items.map((each)=> {
         if(each.id === id) {
           //need to update items with id=2
           return {...each, value}
         }else{
               return each }
       })
      }
      
      console.log(getData("newvalue", 2))


推荐阅读