1

I am trying to configure My API to be suitable with Chart.js

my API contains

{
    "Food": 900,
    "Shopping": 0,
    "Travel": 600,
    "Health": 0
}

it should be like

[
    {
      data:900,
      label: 'Food'
    },

    {
      data: 0,
      label: 'Shopping'
    },

    {
      data: 600,
      label: 'Travel'
    },
    {
      data: 0,
      label: 'Health'
    }
];
1
  • What have you attempted? Commented Jan 24, 2019 at 22:57

4 Answers 4

3

Sure, just iterate through Object.entries and push each prop and label to an array:

const data = { "Food": 900, "Shopping": 0, "Travel": 600, "Health": 0 };
let result = [];
Object.entries(data).forEach(prop => result.push({
  "data": prop[1],
  "label": prop[0]
}));

console.log(result);

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

1 Comment

Please explain @AymanSafi - I don't understand what you mean. Could you edit your question please? What would be an example of this JSON object you're describing?
1

Get an array of of your objects keys using Object.Keys(yourObjectHere) Then you can loop through this array and use the keys to access the value stored for each key in your object. During the same iteration you can add on to your new object. Ex:

var keys = Object.Keys(yourObjectHere)
for(var i = 0; i < keys.length; i++){
    var value = yourObjectHere[keys[i]];
    //add value and keys[i] to your new object
}

Comments

1

I think this would help

let origin = { "Food": 900, "Shopping": 0, "Travel": 600, "Health": 0 };

let newObject = Object.entries(origin).reduce((obj, item) => {
  obj.push({
    "label": item[0],
    "data": item[1]
  });
 return obj;
}, [])

console.log(newObject)

You can watch this video to have a better idea on how reduce works. Good luck!

Comments

1

Its also possible to do it with Object.keys. Here is an example

you can have a look at Object.Keys documentation here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

var data = { "Food": 900, "Shopping": 0, "Travel": 600, "Health": 0 };
let result = [];
Object.keys(data).forEach(prop => 
result.push({
data: data[prop],
label: prop
}));

console.log(result);

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.