0

How can I using a loop to improve this jquery code?

$.getJSON("@Url.Action("GetPainel", "Home")", {}, function(data) {
  var json = data;
  var PieData = [{
    value: data[0].value,
    color: data[0].color,
    highlight: data[0].highlight,
    label: data[0].label
  },{
    value: data[1].value,
    color: data[1].color,
    highlight: data[1].highlight,
    label: data[1].label
  }];

2 Answers 2

3

You don't event need a loop**, you can just use map() to build a new array of objects from the one retrieved from your AJAX request:

$.getJSON("@Url.Action("GetPainel", "Home")", function(data) {
  var pieData = data.map(function(o) {
    return {
      value: o.value,
      color: o.color,
      highlight: o.highlight,
      label: o.label
    }
  }

  // work with pieData here...
});

** I mean explicit loop. I realise that map() loops internally.

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

4 Comments

elegant and efficient solution. Kudos.
It would be kinda silly to map over data if each element has just 4 keys and he's trying to copy it over...
@KarelG I agree, although I'm giving the OP the benefit of the doubt that they wouldn't be asking that question if it were possible to transpose an existing array
Very simple. Thx.
0

You can make it like this

 $.getJSON("@Url.Action("GetPainel", "Home")", {}, function (data) {
    var PieData=[];
    data.forEach(function(entry){
        PieData.push({
          value:entry.value,
          color:entry.color,
          highlight:entry.highlight,
          label:entry.label
       });
    });

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.