10

In my angular application i am getting an Json Data like below.

[{"id":"5","name":"Immidiate"},
{"id":"4","name":"30 days"},
{"id":"3","name":"21 days"},
{"id":"2","name":"14 days"},
{"id":"1","name":"7 days"},
{"id":"6","name":"Custom"}]

I need an output like below,

[{"Name":"5","Data":"Immidiate"},
{"Name":"4","Data":"30 days"},
{"Name":"3","Data":"21 days"},
{"Name":"2","Data":"14 days"},
{"Name":"1","Data":"7 days"},
{"Name":"6","Data":"Custom"}]

Here is my code

$rootScope.DashboardData["Name"] =  widget.seriesname ;
delete $rootScope.DashboardData[widget.seriesname];                
$rootScope.DashboardData["data"] =  widget.dataname ;
delete $rootScope.DashboardData[widget.seriesname];
widget.chartSeries = $rootScope.DashboardData;

where widget.seriesname is "id" and widget.dataname is "name".

Problem: Key is not changed!

6 Answers 6

18

Use the map function:

var array = [{"id":"5","name":"Immidiate"},
{"id":"4","name":"30 days"},
{"id":"3","name":"21 days"},
{"id":"2","name":"14 days"},
{"id":"1","name":"7 days"},
{"id":"6","name":"Custom"}];

var resultArray = array.map(function(elm) {
   return { Name: elm[widget.seriesname], Data: elm[widget.dataname]};
});
Sign up to request clarification or add additional context in comments.

4 Comments

the new keys are in the object your return inside the map function ("Name","Data")
so i should pass inside this method one by one element?
no its the entire array. look at my edit, your output is the resultArray variable
now i have id and name in a variable. so how can i get the value without hardcoding the id and name?
11
const arr = [{"id":"5","name":"Immidiate"},
{"id":"4","name":"30 days"},
{"id":"3","name":"21 days"},
{"id":"2","name":"14 days"},
{"id":"1","name":"7 days"},
{"id":"6","name":"Custom"}];

const resultArray = arr.map(elm => ({ Name: elm.id, Data: elm.name}));

console.log(resultArray);

Comments

2

EDIT: Just seen your angular tag - use angular's forEach:

var out = [];

angular.forEach(data, function (obj) {
    out.push({
        Name: obj.id,
        Data: obj.name
    });
});

Without angular:

For modern browsers, use array.map:

var out = data.map(function (obj) {
   return {
        Name: obj.id,
        Data: obj.name
    };
});

console.log(out);

And in older browsers:

var data = [{"id":"5","name":"Immidiate"},
           {"id":"4","name":"30 days"},
           {"id":"3","name":"21 days"},
           {"id":"2","name":"14 days"},
           {"id":"1","name":"7 days"},
           {"id":"6","name":"Custom"}];

var out = [];

for (var key in data) {
    if (data.hasOwnProperty(key)) {
        out.push({
            'Name': data[key].id,
            'Data': data[key].name
        });
    }
}

console.log(out);

Comments

2

You could also do this:

arr.map(({id, name}) =>({name: id, data:name}))

const objArr = [
    { id: "5", name: "Immidiate" },
    { id: "4", name: "30 days" },
    { id: "3", name: "21 days" },
    { id: "2", name: "14 days" },
    { id: "1", name: "7 days" },
    { id: "6", name: "Custom" },
  ];

objArr.map(({id, name}) =>({name: id, data:name}))

2 Comments

Interesting. Since the map function didn't explicitly describe the syntax with {id, name}, I had to dig a bit: It's a general javascript feature (not just for map) called "Object destructuring".
Indeed, I wrote a little bit about that with some questions here: coderanx.com/javascript/…
1

You can also use Underscopre.js map method:

$scope.newList = _.map(list, function(item) {
 return { Name: item.id, Data: item.name};
});

See Example in Fiddle


Comments

1
var books = {
  "mainKey1": {
    "History" : [
      {"hai" : "hello"},
      {"hai" : "bye"}
    ],
    "tempKey" : "tempValue"
  },
  "mainKey2":{
    "Number": "AD-3424",
    "Number1": "AD-3424"
  },
  "temparr" : [
    "ai",
    "bi"
  ]

};

function replaceKeys(books,replacementkeys,newKeyJson) {
  if(typeof books == 'object') {    
    newKeyJson = Object.keys(books).map((book) => {
      if(typeof books[book] == 'object' || Array.isArray(books[book]) ) {
        replaceKeys(books[book],replacementkeys,newKeyJson[book])
      }
      if(replacementKeys[book]) {
          newKeyJson[replacementKeys[book]] = books[book];          
          delete newKeyJson[book];          
      }
    })

  }
  else if(Array.isArray(books)) {
   for( var i=0;i< books.length;i++) {
        replaceKeys(books[i],replacementkeys,newKeyJson[i]);
   }
  }else if(typeof books == 'string') {
    return;
  }else {
    return;
  }
}

var replacementKeys = {"History" : "replaced History","hai" : "hi","Number" : "test","Number1" : "test2","mainKey1" :"sidekey","tempKey" : "realKey","mainKey2" :"side2"};
var newKeyJson = Object.assign({},books);
replaceKeys(books,replacementKeys,newKeyJson);
console.log(newKeyJson); //this will contain object with updated keys

1 Comment

please provide info in terms of how it helps answer the question

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.