1

I have this data in var output (this is just an excerpt):

{
  'us-tx-021': 5,
  'us-tx-029': 3,
  'us-tx-031': 1,
}

I need to convert it to something like this:

[
  {
    'hc-key': "us-tx-021",
    'value': 5
  },
  {
    'hc-key': "us-tx-029",
    'value': 3
  },
  {
    'hc-key': "us-tx-031",
    'value': 1
  }
]

I don’t know how to use the keys & values from one object as values for another object. Can anyone help me?

1

1 Answer 1

1

You can use a for loop to get all keys from original json

var json = '{ "us-tx-0212": 5, "us-tx-029": 3, "us-tx-031": 1}';
var obj = JSON.parse(json);

var translatedObj = [];
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        translatedObj.push({'key': key, 'value': obj[key] });
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

{ 'us-tx-021': 5, 'us-tx-029': 3, 'us-tx-031': 1} is not json, right?
@Vohuman: it's a valid json. Unfortunately I don't get what you're trying to say
It seems you don't know what JSON is. JSON is a string. { 'us-tx-021': 5, 'us-tx-029': 3, 'us-tx-031': 1} is a JavaScript object.
@Vohuman: I see where you're trying to get. Fixed my example to avoid confusions
Yes, that makes more sense. But OP didn't mention he/she is using JSON. Also that string is still not a valid JSON :) I just meant to say that using a different variable name is better than json for an object.

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.