red red - 2 months ago 9
Javascript Question

JavaScript - Return object key and value when both are strings

So, I have this array of objects:

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


and I am trying to turn it so that it key and value are like this:

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


But I cannot find a way to grab the key text because it only gives me the
index
.

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


Can someone help me out here? What am I missing?

Answer

You could use Array#map and Object.keys for own properties.

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);