我有一个像这样的对象:
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)) {
results.push(obj[property])
}
}
这里我只得到了价值观。我需要得到以下结果
["property1":1,"property2":2]
代替[1,2]
我试图附加属性名称但它没有所需的结果。
答案 0 :(得分:2)
怎么样:
var results=[];
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
results.push({name: property, value: obj[property]});
}
}
答案 1 :(得分:2)
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);
<强> DEMO 强>
答案 2 :(得分:-1)
您确切想要的解决方案就在这里 -
考虑对象 -
var obj = {
property1: "8898",
property2: "2015-04-27 08:03:39.041",
property3: "27",
property4: "c10",
};
运行此功能后 -
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
var str = obj[property];
results.push(str)
}
}
数组结果将具有值 - 8898,2015-04-27 08:03:39.041,27,c10