Home > Enterprise >  How do I update the value in object if the id matches?
How do I update the value in object if the id matches?

Time:05-06

How do I update the title in data if the id matches?

const data = {
    "0": {
        "id": 1912,
        "title": "Books",
    },
    "1": {
        "id": 1958,
        "title": "Brands",
    },
    "2": {
        "id": 2037,
        "title": "Logo",
    },
    "3": {
        "id": 2038,
        "title": "Colour",
    },
}

For example, This is the object with the latest updated title with the id: 1912.

const updatedData = {id: 1912, title: 'The Books'}

Sample output after updating data with updatedData

const data = {
    "0": {
        "id": 1912,
        "title": "The Books",
    },
    "1": {
        "id": 1958,
        "title": "Brands",
    },
    "2": {
        "id": 2037,
        "title": "Logo",
    },
    "3": {
        "id": 2038,
        "title": "Colour",
    },
}

CodePudding user response:

Use Object.keys() to generate an array of the object keys ([0,1,2,3]). Loop through that array and check the id at each.

const data = {
    0: {
        id: 1912,
        title: 'Books',
    },
    1: {
        id: 1958,
        title: 'Brands',
    },
    2: {
        id: 2037,
        title: 'Logo',
    },
    3: {
        id: 2038,
        title: 'Colour',
    },
};

const updatedData = { id: 1912, title: 'The Books' };

Object.keys(data).forEach((el) => {
    if (data[el].id === updatedData.id) {
        data[el] = updatedData;
    }
});

CodePudding user response:

As for React, I'd suggest that you should mutate your object for the update.

You can use Object.entries to get keys (your indices) and values (your inner object which you want to update), and then use map to populate your updatedData on found data with updatedData.id

const data = {
    "0": {
        "id": 1912,
        "title": "Books",
    },
    "1": {
        "id": 1958,
        "title": "Brands",
    },
    "2": {
        "id": 2037,
        "title": "Logo",
    },
    "3": {
        "id": 2038,
        "title": "Colour",
    },
}

const updatedData = {id: 1912, title: 'The Books'}

const result = Object.entries(data).map(([key, value]) => value.id === updatedData.id ? { [key]: { ...value, ...updatedData } } : { [key]: value })

console.log(result)

  • Related