简体   繁体   中英

Not able to add key value pair in a json object from a json object

I want to add key value pair to my json object from another json object.

I tried to read many stackoverflow similar questions but none of those solutions work in my case.

 const oValues = { action: "Open Browser & Login", password: "something", url: "https://***manage", user: "user1", } var mElementsData = { pages: [{ groups: [{ elements: [{}] }] }] }; for (var key in oValues) { if (oValues.hasOwnProperty(key)) { mElementsData.pages.groups.elements["label"] = key; mElementsData.pages.groups.elements["value"] = oValues[key]; } } console.log(mElementsData);

Your pages , groups and elements elements are all arrays of objects, so you need to reference the specific array element ( [0] ) to set the value:

 var mElementsData = { pages: [{ groups: [{ elements: [{}] }] }] }; var oValues = { key: "value" }; for (var key in oValues) { if (oValues.hasOwnProperty(key)) { mElementsData.pages[0].groups[0].elements[0]["label"] = key; mElementsData.pages[0].groups[0].elements[0]["value"] = oValues[key]; } } console.log(mElementsData);

Pages and groups are array so you have to loop over and bind the object with key and value pair

var mElementsData = {
   pages: [{
        groups: [{
            elements: [{}]
        }]
    }]
};

var oValues = {
    action: "Open Browser & Login",
    password: "something",
    url: "https://***manage",
    user: "user1",
}

for (var key in oValues) {
    if (oValues.hasOwnProperty(key)) {
        for (let i = 0; i < mElementsData.pages.length; i++) {
            let pages = mElementsData.pages[i]
            for (let j = 0; j < pages.groups.length; j++) {
                pages.groups[j].elements[j][key] = oValues[key]
            }
        }
    }
}
console.log(mElementsData)

Your nested properties are not objects, but arrays of objects, so you cannot access them by dot notation. You can access them by index, here is an example:

 const oValues = { action: "Open Browser & Login", password: "something", url: "https://***manage", user: "user1", } var mElementsData = { pages: [{ groups: [{ elements: [] }] }] }; for (var key in oValues) { if (oValues.hasOwnProperty(key)) { const element = { label: key, value: oValues[key] }; mElementsData.pages[0].groups[0].elements.push(element); } } console.log(mElementsData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM