简体   繁体   中英

How to set or change object's attribute name dynamically in javascript (especially in older javascript)

This question has been asked and replied very many times but still I wonder if its possible out of browser to change dynamically an object's attribute name?

I have a bigger problem related to this but I have summarized the core to the one presented now.

var arr = []
var a = "newAttributeName";
var obj2 = {"msg": "hello"};
arr.push({a: obj2});

console.log(JSON.stringify(arr));

In pushing obj2 to array (arr) I would need to change attribute name "a" dynamically (which is variable) to what is given as the value of this variable. But this does not take place. I only have [{"a":{"msg":"hello"}}] in the console. Are there any trick how to change attribute names dynamically especially in non-browser context?

=========================================================================== Ok, I present yet the wider issue of which the question was the part. Below is the working code where in the the attribute dynamicName should be updated according to the value of 3th parameter in the buildNested function. Maybe someone find the way to solve or circumvent the issue.

var parentObj =  
    [
        {"clientid": 0, "name": "Mike"}, 
        {"clientid": 1, "name": "Alan"}, 
        {"clientid": 3, "name": "Peter"},
        {"clientid": 4, "name": "Anna"}
    ];

var childObj =  
    [
        {"address": "address info 1", "clientid": 0}, 
        {"address": "address info 2", "clientid": 1}, 
        {"address": "address info 3", "clientid": 4},
        {"address": "address info 4", "clientid": 3},
        {"address": "address info 5", "clientid": 3}
    ];


console.log(JSON.stringify(buildNested(parentObj, childObj, "givenName", "clientid")));


function buildNested(parentObj, childObj, dynamicName, matchId) {

    var nested = parentObj.reduce(function(acc, item) {
        acc.push(
            Object.assign({}, item,
                {
                    dynamicName_: buildObject(childObj, item, matchId)
                }
            )
        );
        return acc;
    }, []);

    // **** here is the circumvent-solution ****
    nested = JSON.stringify(nested);
    return nested.replace(new RegExp( dynamicName_, 'g' ), dynamicName);
    // ***************************************
}

function buildObject(childObj, parent, matchId) {
    var filtered = childObj.filter(function(x) {
        if (x[matchId] === parent[matchId]) {
            return x;
        }
    })  
    return filtered;
}

使用方括号表示动态属性符号(又称计算属性名称):

arr.push({ [a]: obj2 });

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