我使用map方法将对象转换为数组。以下代码中的问题是什么?
var data = {
"productName": "fsdfsdf",
"productDesc": "",
"category": null,
"categoryName": "",
"style": null,
"styleName": "",
"substyle": null,
"substyleName": "",
"store": null,
"storeName": "",
"stand": null,
"standName": "",
"rack": null,
"rackName": "",
"roll": null,
"rollName": "",
"color": null,
"width": "",
"widthunit": "meter",
"length": 0,
"lengthunit": "meter",
"pieces": "",
"cutofquantity": "",
"estimatedConsumption": ""
}
var key = $.map(data, function(value, index) {
return index;
});
var value = $.map(data, function(value, index) {
return value;
});
console.log(value)
请参阅Matlab documentation JSFiddle以获取实例。
答案 0 :(得分:6)
因为你有length: 0
作为你的一个属性,jQuery认为该对象是一个数组而不是一个对象。
然后循环遍历从0到0(不包括)的数字索引并生成零长度数组。
答案 1 :(得分:1)
如果您想与length:0
var data = {
"productName": "fsdfsdf",
"productDesc": "",
"category": null,
"categoryName": "",
"style": null,
"styleName": "",
"substyle": null,
"substyleName": "",
"store": null,
"storeName": "",
"stand": null,
"standName": "",
"rack": null,
"rackName": "",
"roll": null,
"rollName": "",
"color": null,
"width": "",
"widthunit": "meter",
"length": 0,
"lengthunit": "meter",
"pieces": "",
"cutofquantity": "",
"estimatedConsumption": ""
};
for(var key in data) {
if(data.hasOwnProperty(key)) {
console.log(key) ;
console.log(data[key]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 2 :(得分:0)
您可以执行以下操作:
var data = {
"productName": "fsdfsdf",
"productDesc": "",
"category": null,
"categoryName": "",
"style": null,
"styleName": "",
"substyle": null,
"substyleName": "",
"store": null,
"storeName": "",
"stand": null,
"standName": "",
"rack": null,
"rackName": "",
"roll": null,
"rollName": "",
"color": null,
"width": "",
"widthunit": "meter",
"length": 0,
"lengthunit": "meter",
"pieces": "",
"cutofquantity": "",
"estimatedConsumption": ""
};
var arr = Object.keys(data).map(function(k) { return data[k] });
console.log(arr)
答案 3 :(得分:0)
循环遍历property
的每个object
,然后将key
和value
推送到数组中,如下所示。希望这会对你有所帮助。
var data = {
"productName": "fsdfsdf",
"productDesc": "",
"category": null,
"categoryName": "",
"style": null,
"styleName": "",
"substyle": null,
"substyleName": "",
"store": null,
"storeName": "",
"stand": null,
"standName": "",
"rack": null,
"rackName": "",
"roll": null,
"rollName": "",
"color": null,
"width": "",
"widthunit": "meter",
"length": 0,
"lengthunit": "meter",
"pieces": "",
"cutofquantity": "",
"estimatedConsumption": ""
}
var value = [];
var key = [];
for (var property in data) {
key.push(property);
value.push(data[property]);
}
console.log(value)
&#13;
答案 4 :(得分:-1)
var key = Object.keys(data).map(function(index, value) { return index });
var value = Object.keys(data).map(function(index, value) { return data[index] });
所以它给出了键值和值对