I am using map method to convert from an object to an array. What is the issue in the following code?
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)
Please refer to this JSFiddle for a live example.
To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .
A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs. An array can be considered to be an object with the following properties/keys: Length - This can be 0 or above (non-negative).
Because you have length: 0
as one of your properties, jQuery thinks that the object is an array instead of an object.
It then loops over the numerical indexes from 0 to 0 (not inclusive) and generates a zero length array.
Here is the alternate if you want to use with 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With