How to add data to an object from an array with objects by key?

  • 0
    The object has an id, you need to find an object with the same id in the array and add keys with values ​​from it to the original object, if there is no such object in the first array, then search in the second and add, respectively, from the second. How to do it right?

    1. {id: 1};
    2. [{id: 3, value: 1}, {id:1, value: 4}];
    3. [{id: 2, value: 9}, {id: 4, value: 2}, {id: 1, value: 3}];
    
    в результате должно быть {id: 1, value: 4}
    JavaScript Sophie Odom, Sep 10, 2019

  • 2 Answers
  • 0
    for (const arr of [ arr1, arr2 /* и т.д., можете искать в любом количестве массивов */ ]) {
    const source = arr.find(n => n.id === target.id);
    if (source) {
    Object.assign(target, source);
    break;
    }
    }
    Myles Warner

  • 0
    let data = { id: 1 }
    const first = [{ id: 3, value: 1 }, { id: 1, value: 4 }]
    const second = [{ id: 2, value: 9 }, { id: 4, value: 2 }, { id: 1, value: 3 }]

    let result = first.find(o => o.id === data.id)

    if (!result) {
    result = second.find(o => o.id === data.id)

    if (!result) {
    result = {}
    }
    }

    data = {
    ...data,
    ...result
    }
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!