0

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

0

2 Answers 2

1

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>

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

Comments

0

You could use Map to do this.

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

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.