JavaScript - 当两者都是字符串时返回对象键和值

时间:2016-10-07 16:50:44

标签: javascript

所以,我有这个对象数组:

var obj = [{
    "Has the house been sold?": "N"
}, {
    "Is the house on the market?": "Y"
}, {
    "Duration of Sale": "2 weeks"
}];

我试图把它变成它的关键和值是这样的:

var obj = [
    {key: 'Has the house been sold?', value: 'N'}
];

但我找不到抓取关键文字的方法,因为它只给了我index

for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
        var val = obj[key];
        console.log(val);
    }
}

有人可以帮助我吗?我错过了什么?

4 个答案:

答案 0 :(得分:2)

使用Array.map()

var obj = [{
    "Has the house been sold?": "N"
}, {
    "Is the house on the market?": "Y"
}, {
    "Duration of Sale": "2 weeks"
}];

var newObj = obj.map(function(ea, i){
    var thisKey = Object.keys(ea)[0];
    return {key: thisKey, value: ea[thisKey]};
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

答案 1 :(得分:2)

您可以将Array#mapObject.keys用于自己的属性。

var obj = [{ "Has the house been sold?": "N" }, { "Is the house on the Market?": "Y" }, { "Duration of Sale": "2 weeks" }],
array = obj.map(function (a) {
    var key = Object.keys(a)[0];
    return { key: key, value: a[key] };
});
console.log(array);

ES6

var obj = [{ "Has the house been sold?": "N" }, { "Is the house on the Market?": "Y" }, { "Duration of Sale": "2 weeks" }],
array = obj.map(a => (key => ({ key:key, value: a[key] }))(Object.keys(a)[0]));
console.log(array);

答案 2 :(得分:1)

您需要遍历obj中的每个项目,因为它是一个数组,然后对于每个项目,遍历其属性然后保存它们。

var obj = [{
    "Has the house been sold?": "N"
}, {
    "Is the house on the market?": "Y"
}, {
    "Duration of Sale": "2 weeks"
}];

var newObj = [];

for (var i = 0; i < obj.length; i++) {
  for (var key in obj[i])
  {
    newObj.push({key: key, value: obj[i][key]})
  }
}
console.log(JSON.stringify(newObj))

答案 3 :(得分:1)

或只是使用forEach

var arr = [];
obj.forEach(item => {arr.push({key : Object.keys(item)[0], value : item[Object.keys(item)][0]})})
console.log(arr);