我有像这样的arrya ob对象
myobj= [{"item1" : info in here},{"item2" : info in here}, {"item3" : info in here}]
我试图修改一个只有它的钥匙才能找到它。所以我会收到发送" item1"我需要确定该对象,以便我可以更改其值(值是随机的,我不会知道它们,所以我不能依靠使用它们来识别。
我的想法是,如果我能得到项目的索引就很容易了,我可以做myobj [index] .value = newvalue。
也许索引不是最好的方式(我对其他想法持开放态度)但是,有没有办法在该数组中找到对象索引?谢谢! (如果有帮助,我也会使用下划线)
编辑:
我以为我可以尝试像
这样的东西myobj.objectVar
其中objectVar是变量名称我被传递(" item1"例如)以匹配,但是这不起作用,可能是因为它是一个变量?是否可以使用这样的变量?
答案 0 :(得分:4)
您对解决方案的猜测并不起作用,因为您没有访问单个对象,而是访问了一组对象,每个对象都有一个属性。
要以您现在拥有的格式使用数据,您需要遍历外部数组,直到找到包含您之后的密钥的对象,然后修改其值。
myobj= [{"item1" : info in here},{"item2" : info in here}, {"item3" : info in here}]
function setByKey(key, value) {
myObj.forEach(function (obj) {
// only works if your object's values are truthy
if (obj[key]) {
obj[key] = value;
}
});
}
setByKey('item1', 'new value');
当然,更好的解决方案是停止使用单属性对象数组,只使用一个具有多个属性的对象:
myobj= {"item1" : info in here, "item2" : info in here, "item3" : info in here};
现在,您可以只使用myObject.item1 = "some new value"
,它会正常工作。
答案 1 :(得分:2)
你可以写一个像
这样的函数function getElementsHavingKey(key) {
var objectsHavingGivenKey = [];
//loop through all the objects in the array 'myobj'
myobj.forEach(function(individualObject) {
//you can use 'hasOwnProperty' method to find whether the provided key
// is present in the object or not
if(individualObject.hasOwnProperty(key)) {
// if the key is present, store the object having the key
// into the array (many objects may have same key in it)
objectsHavingGivenKey.push(individualObject);
}
});
// return the array containing the objects having the keys
return objectsHavingGivenKey;
}
如果您只想获得具有给定键的元素索引
你可以这样做,
function getIndexesOfElementsHavingKey(key) {
var objectsHavingGivenKey = [];
//loop through all the objects in the array 'myobj'
myobj.forEach(function(individualObject, index) {
//you can use 'hasOwnProperty' method to find whether the provided key
// is present in the object or not
if(individualObject.hasOwnProperty(key)) {
//push index of element which has the key
objectsHavingGivenKey.push(index);
}
});
// returns the array of element indexes which has the key
return objectsHavingGivenKey;
}
答案 2 :(得分:1)
试试这段代码:
function changeObj( obj, key, newval )
{
for( var i=0, l=obj.length; i<j; i++)
{
if( key in obj[i] )
{
obj[i] = newval;
return;
}
}
}
答案 3 :(得分:1)
var myObjArray= [{"item1" : "info in here"},{"item2" : "info in here"}, {"item3" : "info in here"}]
查找并向数组内的对象添加新值:
myObjArray.forEach(function(obj) {
for(var key in obj) {
// in case you're matching key & value
if(key === "item1") {
obj[key] = "update value";
// you can even set new property as well
obj.newkey = "New value";
}
}
});
答案 4 :(得分:1)
您可以使用索引访问相同的对象,甚至是原始对象内的对象。
这是你要找的东西:
var otherObj = [{"oitem":"oValue"}];
var myobj= [{"item1" : otherObj},{"item2" : "2"}, {"item3" : "tesT"}];
myobj[0].item1[0].oitem = "newvalue";
alert(myobj[0].item1[0].oitem);