yanivz
yanivz

Reputation: 158

Rearrange object using AngularJS forEach

I want to rearrange an object in AngularJS which looks like this:

var persons = [
  {socialnum : "123", pname: "Malcom Reynolds"},
  {socialnum : "456", pname: "Kaylee Frye"},
  {socialnum : "789", pname: "Jayne Cobb"}
];

Result should be like this:

var persons = [
  {socialnum : "123", pname: "123 - Malcom Reynolds"},
  {socialnum : "456", pname: "456 - Kaylee Frye"},
  {socialnum : "789", pname: "789 - Jayne Cobb"}
];

What i tried is this:

angular.forEach(persons , function (key, value) {    
this.push(values.socialnum + ' - ' + values.pname);    
}, persons );

I did not received the output i wanted

Upvotes: 0

Views: 24

Answers (2)

Deepu
Deepu

Reputation: 213

Try below code.... since you are already have the array and trying to edit its value, no need to add push function. Just need to update value as given below

var persons = [
  {socialnum : "123", pname: "Malcom Reynolds"},
  {socialnum : "456", pname: "Kaylee Frye"},
  {socialnum : "789", pname: "Jayne Cobb"}
];


angular.forEach(persons , function (key, value) {  
key['pname'] = key['socialnum']+' - '+ key['pname']   
}, persons );
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

Upvotes: 1

Igor
Igor

Reputation: 62238

You could use Map to do this.

let newArray = persons.map(value => {
  return {socialnum: value.socialnum, pname: value.socialnum + ' - ' + value.pname};
});

Upvotes: 0

Related Questions