I have an object like:
我有一个像这样的对象:
obj {
property1: "8898"
property2: "2015-04-27 08:03:39.041"
property3: "27"
property4: "c10"
}
I need to convert this to an array.
我需要将其转换为数组。
My code:
var results=[];
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
results.push(obj[property])
}
}
Here i am getting only the values. I need to have the following result ["property1":1,"property2":2]
instead of [1,2]
在这里,我只得到价值观。我需要得到以下结果[“property1”:1,“property2”:2]而不是[1,2]
I tried to append the property name but it did not have the desired result.
我试图附加属性名称,但它没有所需的结果。
3 个解决方案
#1
var obj = {
property1: "8898",
property2: "2015-04-27 08:03:39.041",
property3: "27",
property4: "c10",
};
var results = [];
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
var str = property +':'+ obj[property];
results.push(str)
}
}
alert(results);
#2
How about:
var results=[];
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
results.push({name: property, value: obj[property]});
}
}
#3
The solution that you exactly want is here-
您确切想要的解决方案是 -
Considering the object-
考虑到对象 -
var obj = {
property1: "8898",
property2: "2015-04-27 08:03:39.041",
property3: "27",
property4: "c10",
};
Once you run this function-
一旦你运行这个功能 -
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
var str = obj[property];
results.push(str)
}
}
The array results will have values - 8898,2015-04-27 08:03:39.041,27,c10
数组结果将具有值 - 8898,2015-04-27 08:03:39.041,27,c10
#1
var obj = {
property1: "8898",
property2: "2015-04-27 08:03:39.041",
property3: "27",
property4: "c10",
};
var results = [];
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
var str = property +':'+ obj[property];
results.push(str)
}
}
alert(results);
#2
How about:
var results=[];
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
results.push({name: property, value: obj[property]});
}
}
#3
The solution that you exactly want is here-
您确切想要的解决方案是 -
Considering the object-
考虑到对象 -
var obj = {
property1: "8898",
property2: "2015-04-27 08:03:39.041",
property3: "27",
property4: "c10",
};
Once you run this function-
一旦你运行这个功能 -
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
var str = obj[property];
results.push(str)
}
}
The array results will have values - 8898,2015-04-27 08:03:39.041,27,c10
数组结果将具有值 - 8898,2015-04-27 08:03:39.041,27,c10