简体   繁体   English

在数组中查找对象,然后对其进行编辑

[英]Find object in array and then edit it

Let's say I have the following array: 假设我有以下数组:

var things = [
    {
        id: "12345",
        name: "Bryan"
    },
    {
        id: "55555",
        name: "Justin"
    }
]

I want to search for the object with the id of 55555 . 我想搜索ID55555的对象。 But I want to update the name of that particular object to " Mike " from Justin but still keep the entire army intact. 但是我想将特定对象的名称从贾斯汀(Justin)更新为“ 迈克(Mike) ”,但仍保持整个部队的完整。

At the moment, I kinda figured out a way to search for the object, but I can't find a solution to actually edit that particular finding. 目前,我有点想出一种搜索对象的方法,但是我找不到真正编辑该特定发现的解决方案。

Could anyone help me out? 有人可以帮我吗? This is what I have so far: 这是我到目前为止的内容:

var thing = things.filter(function (item) {
    return "55555" === item.id;
})[0]

How about a function that finds the correct ID and changes the name 如何找到正确的ID并更改名称的函数

 var things = [ { id: "12345", name: "Bryan" }, { id: "55555", name: "Justin" } ] function updateThings(id, value, arr) { arr.forEach(function(item) { if (item.id == id) { item.name = value; return false; } }); } updateThings("55555", "Mike", things); document.body.innerHTML = '<pre>' + JSON.stringify(things, null, 4) + '</pre>'; 

I would just loop over the array, check if the ID matches and edit the name. 我只是遍历数组,检查ID是否匹配并编辑名称。

for (var i = 0; i < things.length; i++) {
    if (things[i].id == "55555") {
        things[i].name = "new name";
    }
}

Using .filter() is inefficient since it keeps iterating after it finds the item you are looking for. 使用.filter()效率低下,因为它在找到所需的项目后会不断进行迭代。


You could define a generic function like this: 您可以定义一个通用函数,如下所示:

function findElementByPropertyValue(arr, propertyName, propertyValue) {
    for (var i = 0, count = arr.length; i < count; i++) {
        var element = arr[i];
        if (element[propertyName] === propertyValue) {
            return element;
        }
    }
    return null;
}

And then use it like this: 然后像这样使用它:

var mike = findElementByPropertyValue(things, 'id', '55555');
if (mike) {
    mike.name = 'Mike';
}

jsfiddle jsfiddle


If you need to alter a lot of elements in the array, you may want to create a hash object instead. 如果需要更改数组中的许多元素,则可能需要创建一个哈希对象。

function createHashByProperty(arr, propertyName) {
    var hash = {};
    for (var i = 0, count = arr.length; i < count; i++) {
        var element = arr[i];
        hash[element[propertyName]] = element;
    }
    return hash;
}

You can use it like this: 您可以像这样使用它:

var hash = createHashByProperty(things, 'id');

hash['55555'].name = 'Mike'; // Was 'Justin'
hash['12345'].name = 'Brian'; // Was 'Bryan'

jsfiddle jsfiddle


The two functions above do not alter the array, they just allow you to get references to the elements in the array, so you can alter those elements. 上面的两个函数不会更改数组,它们只是允许您获取对数组中元素的引用,因此您可以更改这些元素。

If you want to remove an element from the array, you will need to get its index. 如果要从数组中删除元素,则需要获取其索引。 You can then use the Array.prototype.splice function to remove the element. 然后,您可以使用Array.prototype.splice函数删除该元素。

Here is a function that does this: 这是执行此操作的函数:

function removeElementByPropertyValue(arr, propertyName, propertyValue) {
    for (var i = 0, count = arr.length; i < count; i++) {
        if (arr[i][propertyName] === propertyValue) {
            arr.splice(i, 1);
            return;
        }
    }
}

You can use it like this: 您可以像这样使用它:

removeElementByPropertyValue(things, 'id', '55555');

jsfiddle jsfiddle


Note: The code in this answer uses plain JavaScript; 注意:此答案中的代码使用纯JavaScript; It is not dependent on the jQuery library. 它不依赖于jQuery库。

To be efficient, you could store the locations of each item and then use that to reference the name: 为了提高效率,您可以存储每个项目的位置,然后使用它来引用名称:

var things = [
    {
        id: "12345",
        name: "Bryan"
    },
    {
        id: "55555",
        name: "Justin"
    }
], reference  = things.map(function(a){ return a.id });;

function replace (id, name, ar, ref) { ref.indexOf(id)>-1&&(ar[ref.indexOf(id)]['name']=name); }

replace("55555", "Phil", things, reference);

In this, you will only need to loop one time. 在这种情况下,您只需要循环一次。 Then all the information is stored in the reference variable. 然后,所有信息都存储在reference变量中。 reference stores where the id is, which we use to avoid looping. reference存储id所在的位置,我们使用它来避免循环。 I'm not sure what the compiler is doing and whether it loops or not but this just feels more efficient. 我不确定编译器在做什么,是否会循环,但这更有效率。

.indexOf isn't completely supported so you can use a PollyFill 不完全支持.indexOf,因此您可以使用PollyFill

Add this code to the top of the JavaScript file: 将此代码添加到JavaScript文件的顶部:

[].indexOf||(Array.prototype.indexOf=function(a,b,c){for(c=this.length,b=(c+~~b)%c;b<c&&(!(b in this)||this[b]!==a);b++);return b^c?b:-1;})

and

Array.prototype.map||(Array.prototype.map=function(r,t){var n,o,e;if(null==this)throw new TypeError(" this is null or not defined");var i=Object(this),a=i.length>>>0;if("function"!=typeof r)throw new TypeError(r+" is not a function");for(arguments.length>1&&(n=t),o=new Array(a),e=0;a>e;){var p,f;e in i&&(p=i[e],f=r.call(n,p,e,i),o[e]=f),e++}return o});

along with: 随着:

Array.prototype.forEach||(Array.prototype.forEach=function(r,t){var o,n;if(null==this)throw new TypeError(" this is null or not defined");var e=Object(this),i=e.length>>>0;if("function"!=typeof r)throw new TypeError(r+" is not a function");for(arguments.length>1&&(o=t),n=0;i>n;){var a;n in e&&(a=e[n],r.call(o,a,n,e)),n++}});

Retrieved from: here , here , and here 取自: 这里这里这里

Note: While IE 8 and below don't support indexOf practically every other browser does. 注意:虽然IE 8和更低版本不支持indexOf实际上几乎所有其他浏览器都支持indexOf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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