Reputation: 35
I'm trying to convert an object like {fieldName: "value"}
into another object like {field: "fieldName", value: "value"}
in the simplest way possible, without knowing what the fieldName is in advance.
I've looked at the answer to How to convert string as object's field name in javascript but although this works it relies on the fact that the fieldName is already known. The following works:
const key = Object.keys(searchObject)[0];
return { field: key, value: searchObject[key] }
But it looks unwieldy, clunky and error-prone. What I would like is the equivalent of
const obj = { field: [searchObject.key], ... }
But this only works where [searchObject.key]
is the value of searchObject.key
.
Upvotes: 0
Views: 1518
Reputation: 7933
Iterate over each property in your object and create another one with the key and value as separated properties, then push it to a new array and return it.
Example:
var test_data = {fieldName: "name", fieldName2: "name2"}
function convert(data){
var result = []
for(var k in data){
result.push({
field: k,
value: data[k]
})
}
return result
}
console.log(convert(test_data))
// ------ ES6 ---------- //
console.log(
Object.keys(test_data).map(a=>({field: a, value: test_data[a]}))
)
Upvotes: 2