动态密钥名称 [英] Dynamic key names

查看:84
本文介绍了动态密钥名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过在元素的初始即公共前缀中传递一个整数来动态地从循环生成对象元素。

I am trying to generate object elements dynamically from a loop by passing an integer in the initial i.e common prefix of the elements.

像这样:

           if(inventory.inventory_obj.length){
                obj.inventory_length = inventory.inventory_obj.length;
                for(var x=0; x < inventory.inventory_obj.length; x++){

                    obj.warehouse_+x = inventory.inventory_obj[x].warehouse;
                    obj.name_+x = inventory.inventory_obj[x].name;
                    obj.space_+x = inventory.inventory_obj[x].space;
                    obj.cost_+x = inventory.inventory_obj[x].cost;
                    obj.quantity_+x = inventory.inventory_obj[x].quantity;
                    obj.level_+x = inventory.inventory_obj[x].level;
                    obj.status_+x = inventory.inventory_obj[x].status;
                    obj.deleted_+x = inventory.inventory_obj[x].deleted;
                }
            }

执行上述操作我得到 分配中的左侧无效错误

Doing the above I get "Invalid left-hand side in assignment" error

我已通过console.log(inventory.inventory_obj)测试了inventory.inventory_obj并进行了验证它有所需的值。

I have tested the inventory.inventory_obj through console.log(inventory.inventory_obj) and verified that it has the needed values.

我做的其他尝试包括

                    obj.warehouse_+""+x = inventory.inventory_obj[x].warehouse;
                    obj.warehouse+"_"+x = inventory.inventory_obj[x].warehouse;
                    obj.warehouse_+x.toString() = inventory.inventory_obj[x].warehouse;
                    obj.warehouse.concat("_"+x+"") = inventory.inventory_obj[x].warehouse;
                    //Eliminating the underscore
                    obj.warehouse+x = inventory.inventory_obj[x].warehouse;

以上所有都失败了。

请有人帮我理解我做错了什么。

Please someone help me understand what I am doing wrong.

推荐答案

要动态创建属性名称,请使用方括号:

To create the property name dynamically, use the square bracket notation:

obj['warehouse_' + x] = nventory.inventory_obj[x].warehouse;

这篇关于动态密钥名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆