1

I'd like to convert this object that I receive from server to a JSON file so that I can use it in d3.js chart:

data = {
   "dog ":"5",
   "cat ":"4",
   "fish ":"12",
}

The output should be:

{    
    "name" : "animal",
    "children" : [
        {"name":"dog", "value": 5},
        {"name":"cat", "value": 4},
        {"name":"fish", "value": 10}
    ]
}

What I came up with is:

   var jsonText = [] ;
   for ( key in data) {
  jsonText.push({name : key.trim(), value : parseInt(data[key])});
 }

But when I try to print out the object, I receive:

[object Object],[object Object],[object Object]

In addition to that I have no clue how to add other attributes to the JSON file. So appreciate your hints.

7
  • console.log(JSON.stringify(object)); Commented Jul 7, 2018 at 6:25
  • @CertainPerformance sorry, I corrected the typo. Commented Jul 7, 2018 at 6:25
  • Where are you getting the name:animal data from? The data I'm seeing from your snippet never tells you that. Commented Jul 7, 2018 at 6:26
  • @OscarGodson True. that's part of the problem. I have no clue how to add it to the json from the javascript object. Commented Jul 7, 2018 at 6:28
  • Well, I mean, where does the word "animal" come from? Commented Jul 7, 2018 at 6:29

7 Answers 7

2

You can use Object.keys(data) and loop through the key to get the desired object structure.

var data = {
 "dog ":"5",
 "cat ":"4",
 "fish ":"12",
};
var res = {
  name: "animal",
  children: []
};
Object.keys(data).forEach((key)=>{
  res.children.push(
   {name:key.trim(), value: parseInt(data[key])}
  );
});

console.log(res);

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

1 Comment

Why not simply use for (key in data)? As a bonus, that would also work for non-enumerable objects.
2

You're almost there (the array is formatted correctly), but you need the resulting array to be the value of the children property of the object. It would also be a bit easier to use Object.entries and map, which tranforms an array into another array based on the same elements:

const data = {
   "dog ":"5",
   "cat ":"4",
   "fish ":"12",
};
const children = Object.entries(data)
  .map(([name, value]) => ({ name: name.trim(), value: Number(value) }));
const output = { name: 'animal', children };
console.log(output);

1 Comment

Nice! Just need the values to be int.
2

Assuming you're manually adding a key like animal this should work and the values should be ints.

var data = {
   "dog ":"5",
   "cat ":"4",
   "fish ":"12",
}

var children = Object.keys(data).map((key) => {
  return {
    name: key.trim(),
    value: parseInt(data[key])
  }
})

let result = JSON.stringify({
  name: 'animal',
  children
})

console.log(result);

That will return

{"name":"animal","children":[{"name":"dog ","value":5},{"name":"cat ","value":4},{"name":"fish ","value":12}]}

1 Comment

@Babr how about this?
1

Try - console.log(JSON.stringify(jsonText))

Comments

1

Create an object with children key and push value to it

let data = {
  "dog ": "5",
  "cat ": "4",
  "fish ": "12",
}

let newObj = {
  "name": "animal",
  "children": []
}
for (let keys in data) {
  newObj.children.push({
    name: keys.trim(),
    value: parseInt(data[keys], 10)
  });
}
console.log(newObj)

Comments

1

You could do something like this

    const data = {
       "dog ":"5",
       "cat ":"4",
       "fish ":"12",
    }

    Object.keys(data).reduce((obj, animal) => ({
      ...obj,
      children: [
          ...obj.children,
          {
              name: animal,
              value: data[animal]
          }
      ]
    }), {name: "animal", children: []})

    console.log(JSON.stringify(obj))

This is a cleaner way to get the desired results in my opinion

Comments

1

You can just iterate over the data object using for..in and push prop: value pair objects into you children array:

const data = {
   "dog ": "5",
   "cat ": "4",
   "fish ": "12",
}

let obj = {
  name: "animal",
  children: []
}

for (prop in data) {
  let animal = {}
  animal[prop.trim()] = Number(data[prop])
  obj.children.push(animal)
}

console.log(JSON.stringify(obj))

Comments

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.