我有一个像这样的对象格式:
var groupArray=[{
name: "blabla bla",
code: "1"
},
{
name: "blabla bla2",
code: "12"
},
{
name: "blabla bla3",
code: "123"
}];
我会把它转换成这个结构
var groupArray=[{
type: "Grp",
code: "1"
},
{
type: "Grp",
code: "12"
},
{
type: "Grp",
code: "123"
}];
这是一个JSFiddle演示
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
}
我的问题是,当我点击按钮更改对象的结构时,我没有结果
答案 0 :(得分:2)
您正在尝试访问不存在的索引。
将新元素推送到新数组。
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>
使用函数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>