我在下面找到了这段代码:
var this.something = {};
var box = {};
box.id = X[0];
box.name = X[1]
box.address = X[2];
if(!this.something.ids[box.id]){
this.something.ids[box.id] = 1;
this.something.datas.push(box);
}
如何更改“this.something”数据结构中“box.id”=“z”的“box.name”?
任何人都可以帮助我吗?
我需要引用“this.something”并编辑相关的“box”数组。但是,我不知道如何。
感谢。
答案 0 :(得分:1)
首先,您不能将属性声明为变量:var this.something = {}
是错误的。请改用this.something = {}
。
什么是X
对象?而不是将this.something
作为对象{}
,其属性为数组.ids
和.datas
,您应该使用this.something
作为数组[]
,然后将其推到那里box
对象。然后你可以简单地循环你的数组并只对那些元素进行更改,你正在搜索id。
//Better use array, not object with 2 properties of arrays for ids and objects.
this.something = [];
//Create box object and push to array.
var box = {
id: X[0],
name: X[1],
address: X[2]
}; //You also can create object as you did, but this way is short-hand definition of object with custom properties.
//Push box to array
this.something.push(box)
var boxIdToChange = 'abc';
// Instant edit when you still have access to your 'box' object.
if (box.id === boxIdToChange){
//Make your changes to 'elem' object here.
elem.name = 'New name';
elem.address = 'Different address than original';
}
// If you want to make changes later, for example after creating multiple box elements.
for (var i = 0; i<this.something.length;i++){
var elem = this.something[i];
if (elem.id === boxIdToChange){
//Make your changes to 'elem' object here.
elem.name = 'New name';
elem.address = 'Different address than original';
}
}
答案 1 :(得分:1)
简单地做
for(var i = 0; i < this.something.datas.length; i++){
var box = this.something.datas[i];
if(box.id === 'z'){
box.name = "New Name";
}
}
你可以把它变成一个功能
var Something = function(){
this.ids = [];
this.datas = [];
this.addBox = function(X){
var box = {};
box.id = X[0];
box.name = X[1]
box.address = X[2];
if(!this.ids[box.id]){
this.ids[box.id] = 1;
this.datas.push(box);
}
}
this.getBoxById = function(id){
for(var i = 0; i < this.datas.length; i++){
var box = this.datas[i];
if(box.id === id){
return box;
}
}
return undefined;
}
}
var something = new Something();
...
var box = something.getBoxById('z');
if(box){
box.name = "new name";
}
答案 2 :(得分:0)
如果我得到你所说的话,不应该只是:
if (box.id == "z") box.name = "whatever";
是你在寻找什么?