根据索引替换数组中的对象 [英] replace object in array base on index

查看:344
本文介绍了根据索引替换数组中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在使用react并且我需要继续将对象添加到对象数组中(对象可能具有相同的 index ,这就是为什么我要检查标签索引)。当我要添加的对象与该数组中已有的对象具有相同的 label 属性时,应替换上一个对象。因此,可以说,每个标签只有一个对象。在使用一个以上的标签之前,我所拥有的一直有效。当我这样做时,数组为每个标签 ...

So, Im using react and I need to keep adding objects to an array of objects (object may have the same index, thats why I check for label and index). When the object that I want to add has the same label property as one that already is in that array, it should replace the previous object. So, lets say, only one object for each label. What I have works until I work with more then one label. When I do so, the array accepts more than one objects for each label...

 if (this.state.thumbnailsAtivas.some(thumbnail => {
     thumbnail.index === textura.index
 }) && this.state.thumbnailsAtivas.some(thumbnail => {
     thumbnail.label === textura.label
 })) {
     console.log("already in array");
 }
 else if (this.state.thumbnailsAtivas.some(thumbnail => thumbnail.label === textura.label)) {
     console.log("label already with item");
     this.state.thumbnailsAtivas.some((thumbnail, index) => {
         const tempData = (this.state.thumbnailsAtivas).slice(0);
         tempData[index] = textura;
         this.setState({thumbnailsAtivas: tempData})
     })
 } else {
     this.setState({thumbnailsAtivas: [...this.state.thumbnailsAtivas, textura]},);
 }


推荐答案

您可以使用另一个Array函数称为 findIndex 的用法与 some 相同,但返回的结果类似于 indexOf 可以(返回数组中元素的索引;如果没有元素匹配,则返回 -1 ):

You can use another Array function called findIndex which have the same usage as some but returns a result like indexOf does (returns the index of the element in an array or -1 if no element matches):

let index = this.state.thumbnailsAtivas.findIndex(
    thumbnail => thumbnail.label === textura.label
);

if(index !== -1) {
    this.state.thumbnailsAtivas[index] = yourNewObject;
}

注意::稍微优化一下代码,您可以摆脱对 some 的调用,并使用 findIndex (一次)检查是否存在并查找索引

Note: To optimise your code a little bit, you could get rid of the call to some and use findIndex (once) for both checking existence and finding the index.

这篇关于根据索引替换数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆