简体   繁体   中英

Change javascript object structure

I have an object format like this :

var groupArray=[{
  name: "blabla bla",
  code: "1"
},
{
  name: "blabla bla2",
  code: "12"
},
{
  name: "blabla bla3",
  code: "123"
}];

I would transform it to this structure

var groupArray=[{
  type: "Grp",
  code: "1"
},
{
  type: "Grp",
  code: "12"
},
{
  type: "Grp",
  code: "123"
}];

Here's a JSFiddle demo

function update() {
  var array = "";
  var arrayreturn = this.getPrice(this.groupArray);
  alert(arrayreturn)
  arrayreturn.map(function(elm) {
    this.array += elm + " ";
  });
  document.getElementById("objectTransform").innerHTML = array;
}

var groupArray = [{
    name: "blabla bla",
    code: "1"
  },
  {
    name: "blabla bla2",
    code: "12"
  },
  {
    name: "blabla bla3",
    code: "123"
  }
];

function getPrice(array) {
  var newObject = [{
    typeObject: "",
    code: ""
  }];
  for (var i = 0; i < array.length; i++) {
    newObject[i].typeObject = "group";
    newObject[i].code = array[i].code
  }
  return newObject
}

My problem is when I click on the button to change the structure of my object I got no result

You're trying to access to an index that doesn't exist.

Just push the new elements to the new array.

 function update() { var array = ""; var arrayreturn = this.getPrice(this.groupArray); console.log(arrayreturn) arrayreturn.map(function(elm) { this.array += elm + " "; }); document.getElementById("objectTransform").innerHTML = array; } var groupArray = [{ name: "blabla bla", code: "1" }, { name: "blabla bla2", code: "12" }, { name: "blabla bla3", code: "123" }]; function getPrice(array) { var newObject = []; for (var i = 0; i < array.length; i++) { newObject.push({ type: 'Grp', code: array[i].code }); } return newObject } 
 <button onClick="update();">Click me</button> <div id="objectTransform">PRICE HERE</div> 

An alternative using the function map

 function update() { var array = ""; var arrayreturn = this.getPrice(this.groupArray); console.log(arrayreturn) arrayreturn.map(function(elm) { this.array += elm + " "; }); document.getElementById("objectTransform").innerHTML = array; } var groupArray = [{ name: "blabla bla", code: "1" }, { name: "blabla bla2", code: "12" }, { name: "blabla bla3", code: "123" }]; function getPrice(array) { return array.map(function(o) { return { type: 'Grp', code: o.code } }); } 
 <button onClick="update();">Click me</button> <div id="objectTransform">PRICE HERE</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM