Search code examples
javascriptreactjsobjectstate

JS React: Two Objects, change properties if name matches


i have a problem with Objects in JavaScript (React).

I have two different Objects, which are generated from two different XML-Files. Each Object has the same Names in it but the points and position can be different. My Goal is to add the Points from the second Object to the First if the name matches.

The Structure of the Objects is the following:

let obj = [{name: "Max", points: 2},{name:"Marc", points: 1}]
let obj2 = [{name:"Marc", points: 2},{name: "Max", points: 1}]

The Goal is to have one updated Object:

let updatedObj = [{name: "Max", points:3},{name:"Marc", points:3}]

My Code looks like this rn:

import React, {useState} from 'react'
import axios from 'axios'

const App = () => {

    const [list1,setList1] = useState()
    const [list2,setList2] = useState()

    const readFile = (file, number) => {
        const dayPath = `/files/`;

        axios.post(`http://localhost:5001/getData`, {dayPath, file})
        .then(res => {
            // File Number 1
            if(number === 1){
            let obj = res.data.vehicles[1].vehicle.map((item) => (
            {
              name: item.name,
              points: res.data.vehicles[0] - Number(item.Position) +1 // Vehicles Total - Position + 1
            })
          )  
          setList(obj)
          }else {
            /* 
             * Get second Object -> Map -> Find matching Name ->
             * Keep the Name Value -> (Calculate) and Add Points ->
             * Push to State
             */
          }
          })}
    }

  return (
    <div>App</div>
  )

export default App

I've tried it with Object.entries, but only the last item was updated and the others were empty.

Thanks for your help!


Solution

  • let obj = [{name: "Max", points: 2},{name:"Marc", points: 1}]
    let obj2 = [{name:"Marc", points: 2},{name: "Max", points: 1}]
    
    const updatedObj = obj.map((person)=> {
      const personRes = obj2.find((searchPerson)=> searchPerson.name === person.name)
      if(personRes){
        person.point += personRes.point
      }
      return person 
    })