0

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.

1
  • You might be interested in Object.entries() Commented Oct 3, 2019 at 13:01

1 Answer 1

2

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]}))
)

Sign up to request clarification or add additional context in comments.

1 Comment

The ES6 looks ok, but I'm trying to avoid an array solution. Perhaps that's the best result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.