【问题标题】:javascript create object dynanically by variable valuejavascript通过变量值动态创建对象
【发布时间】:2015-10-07 17:10:22
【问题描述】:

我想根据变量的值创建一个对象。我希望下面的代码可以更好地解释我想要的:

$('.tariffCostState').each(function(){
        var tariffCostObj = $(this).data('tariff-code-name');

/*
    How do I set the value of tariffCostObj as an object ?

[EDIT]
        Imagine that var tariffCostObj='abc';
        I want that abc becomes an object: abc={}
*/
        var testObj={};

        var tariffCostsInput=$(this).find('input.m2m-tariff-costs-input');

        for(var j= 0, inputLen = tariffCostsInput.length; j<inputLen; j++){
            var tariffCostsInputId = $(this).find('input.m2m-tariff-costs-input').eq(j).attr('id');
            var tariffCostsInputValue= $(this).find('input.m2m-tariff-costs-input').eq(j).val();

            testObj[tariffCostsInputId]=tariffCostsInputValue;

            //The goal is to have:
            abc[tariffCostsInputId]=tariffCostsInputValue;



        }
        console.log(testObj);

    });

我想要tariffCostObj (abc, ... ) 而不是一个名为testObj 的对象,testeObj 只是一个示例

谢谢

【问题讨论】:

  • 您的意思是可能像这样? {valueOftariffCostObj :{....}}
  • 请显示预期结果对象的轮廓。不太清楚目标是什么
  • 请记住,您在其中设置的对象仅在.each() 中可见。您是否也希望能够在每个外部访问它?

标签: javascript jquery object javascript-objects


【解决方案1】:

不太清楚,但我认为你想这样做:

var testObj={};
$('.tariffCostState').each(function(){

    var tariffCostObj = $(this).data('tariff-code-name');

    if( 'undefined' === typeof testObj[ tariffCostObj ] ) 
         testObj[ tariffCostObj ] = {};

/*
How do I set the value of tariffCostObj as an object ?
*/


    var tariffCostsInput=$(this).find('input.m2m-tariff-costs-input');

    for(var j= 0, inputLen = tariffCostsInput.length; j<inputLen; j++){
        var tariffCostsInputId = $(this).find('input.m2m-tariff-costs-input').eq(j).attr('id');
        var tariffCostsInputValue= $(this).find('input.m2m-tariff-costs-input').eq(j).val();

       testObj[ tariffCostObj ][tariffCostsInputId]=tariffCostsInputValue;


    }
    console.log(testObj);

});

【讨论】:

  • 进展顺利。但它在主对象内创建了一个空对象。所有属性都应该在动态对象内。我只是编辑帖子以获得更好的解释
【解决方案2】:

这是你想要的吗?

var someObjName = "myObj";
var someObjPropName = "myProp";
var someObjPropValue = "myVal";

window[someObjName] = {};
window[someObjName][someObjPropName] = someObjPropValue;

现在您有了一个名为 myObj 的对象,其中包含一个属性和一个值。

【讨论】:

    猜你喜欢
    • 2014-01-04
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 2012-05-18
    相关资源
    最近更新 更多