brian rockson
brian rockson

Reputation: 41

Replace key and strings in array in JSON

I have this JSON below:

{
    "class": "List",
    "list": [{
            "name": "HandsUp"
            "schedule": {
                "type": "probability",
                "theme": "Regular",
                "occurance": {
                    "next": 1607687249008.9834,
                    "prev": null
                }
            }
        }, {
            "name": "Listing",
            "waitingScreenInfo": {
                "__class": "WaitingScreenInfo",
                "getRecapTime": 1607687753.7949834
            },
            "schedule": {
                "type": "Waiting2",
                "theme": "Listing",
                "occurance": {
                    "next": 1607687249008.9834,
                    "prev": null
                }
            }
        }
    ]
}

and I have this one:

{
    "HandsUp": "HandsDown",
    "Listing": "ImgList",
    "Waiting2": "UpNDown"
}

The equivalent of the strings in the first JSON are in the second JSON and I wonder how can I make a function that finds the equivalents of the strings in the first JSON and then replace all of them even though if there is more than one?

Upvotes: 2

Views: 646

Answers (1)

Aalexander
Aalexander

Reputation: 5004

You can do this

  • Go through the array
  • check if property name equals the key from your "repl" object
  • if yes reassign the value with the one in your "repl" object

let stru = {
    "class": "List",
    "list": [{
        "name": "HandsUp",
        "schedule": {
            "type": "probability",
            "theme": "Regular",
            "occurance": {
                "next": 1607687249008.9834,
                "prev": null
            }
        }
    }, {
        "name": "Listing",
        "waitingScreenInfo": {
            "__class": "WaitingScreenInfo",
            "getRecapTime": 1607687753.7949834
        },
        "schedule": {
            "type": "Waiting2",
            "theme": "Listing",
            "occurance": {
                "next": 1607687249008.9834,
                "prev": null
            }
        }
    }]
}

const repl = {
    "HandsUp": "HandsDown",
    "Listing": "ImgList",
    "Waiting2": "UpNDown"
}

console.log("Before ", stru)

stru.list.forEach(element => {
    // keys and values correspond at the index
    let keys = Object.keys(repl);
    let values = Object.values(repl);
    for (let i = 0; i < keys.length; i++) {
        if (keys[i] === element.name) {
            element.name = values[i];
        }
    }

});


console.log("Afterwards ", stru)

Upvotes: 3

Related Questions