Home > database >  Change event data Object in Object (Array in Array) JavaScript
Change event data Object in Object (Array in Array) JavaScript

Time:11-17

i have this problem. I have array like this:

const a = [{name: 'A'
           car:[{color: 'red',type: 'limbo'},
                {color: 'blue',type: 'yamaha'},
               ]
           }, 
           {name: 'B'
            car:[{color: 'green',type: 'beam'},
                ]
           }
          ].

Nơw I have to create 2 funtion for 2 button:

  • The first when click, add 1 more the car of name === 'A' with {color: 'black',type: 'mitsu'}
  • The second when click, change the car with type === beam of name === 'B' with {color: 'black',type: 'mitsu'}

I'm just new in this type, so can anyone help me? I have try 2 map(), or map() inside find(), but still not work @@. Thank you very much

CodePudding user response:

const a = [{name: 'A'
           car:[{color: 'red',type: 'limbo'},
                {color: 'blue',type: 'yamaha'},
               ]
           }, 
           {name: 'B'
            car:[{color: 'green',type: 'beam'},
                ]
           }
          ].
function addCar(name, car) {
  return a.map(it => {
    let res = it
    if(it.name === name) {
      res.car.push(car)
    }
    return res
  })
}

function changeCar(name, car) {
  return a.map((it, i) => {
    let res = it
    if(it.name === name) {
      let carIdx = res.car.findIndex(it=> it.type === car.type)
      if(carIdx >= 0) {
        a[i].car.splice(carIdx, 1)
      }
    }
    return res
  })}

try this

CodePudding user response:

You can simply achieve this by iterating the input array. Here is the live demo :

const arr = [{
  name: 'A',
  car: [
    {color: 'red',type: 'limbo'},
    {color: 'blue',type: 'yamaha'}
  ]
}, {
  name: 'B',
  car:[{color: 'green',type: 'beam'}]
}];

const replaceObj = { color: 'black', type: 'mitsu' };

function updateA() {
  arr.forEach(obj => {
    if (obj.name === 'A') {
      if (!JSON.stringify(obj.car).includes(JSON.stringify(replaceObj))) {
        obj.car.push(replaceObj);
      }
    } 
  })
  console.log(arr);
}

function updateB() {
  arr.forEach(obj => {
    if (obj.name === 'B') {
      const index = obj.car.findIndex(({ type }) => type === 'beam');
      obj.car[index] = replaceObj;
    } 
  })
  console.log(arr);
}
<button onClick="updateA()">Button A</button>
<button onClick="updateB()">Button B</button>

  • Related