如果我有属性名称,有没有办法将值列表转换为对象?
我需要做的就是这样做,但是在循环中创建对象来处理具有很多属性的对象。
var input = ["item 1 data","item 2 data",["item3a data","item3b data","item3c data"]];
document.write("Input: " + JSON.stringify(input) + "<br>");
var output = {ITEM_1:"item 1 data", ITEM_2:"item 2 data", ITEM_3:["item3a data","item3b data","item3c data"] };
document.write("Output: " + JSON.stringify(output) + "<br>");
document.write("Output item 3: " + JSON.stringify(output.ITEM_3));
// Input:
["item 1 data","item 2 data",["item3a data","item3b data","item3c data"]]
// Output:
{"ITEM_1":"item 1 data","ITEM_2":"item 2 data","ITEM_3":["item3a data","item3b data","item3c data"]}
// Output item 3:
["item3a data","item3b data","item3c data"]
属性的名称可以在列表中。
var names = ["ITEM_1","ITEM_2","ITEM_3"];
答案 0 :(得分:1)
这样的事情应该有效,尽管可能有更优雅的方式。
var output= {};
for (var i=0; i < input.length; i++) {
output[names[i]] = input[i];
}
document.write(JSON.stringify(output))
答案 1 :(得分:1)
尝试
var output = {};
input.map(function(value, i) {
return output[names[i]] = value
});
document.write(JSON.stringify(output))
var input = ["item 1 data","item 2 data",["item3a data","item3b data","item3c data"]];
var names = ["ITEM_1","ITEM_2","ITEM_3"];
var output = {};
input.map(function(value, i) {
return output[names[i]] = value
});
document.write(JSON.stringify(output, null, 4))
答案 2 :(得分:1)
您可以遍历输入并逐个向结果中添加项目:
var propertyList = ["ITEM_1","ITEM_2","ITEM_3"]; //your list of property names
var result = {}; //start with an empty object
input.forEach(function(item,index){ //for each item in your input
result[propertyList[index]]=item; //add one to your result using the respective property name
});
答案 3 :(得分:0)
在制作对象时,可以使用for循环将列表项与属性名称对齐。
function listToObject(list, properties) {
var obj = {};
for (var i = 0; i < list.length; i++) {
obj[properties[i]] = list[i];
}
return obj;
}