是否在对象数组内循环?

问题描述 投票:0回答:1

我的问题是更新一个包含对象的数组,每个对象包含一个数组,我想更新全局数组,其值引用对象内部的数组,这种逻辑!

generalArray = [{name:String, features:String[]}]

// Try edit message
let array1 = [{ name: "num", features: ['id']  },
            { name: "cat", features: ['gender'] }];
ob = {name:'num2', features:['id']};

function updateArr(arr,ob){

  const index = arr.findIndex(x => 
      ob.features.toString() === x.features.toString()
                              );
    if (index === -1) {
        arr.push(ob);
    } else {
        arr[index] = ob;
    }
}
console.log(array1);
updateArr(array1,ob);
console.log(array1);

这在任何对象的特征数组包含一个字符串的情况下都可以正常工作,但是如果它包含多个字符串,则exm features = ['id','gender']则无能为力!请帮助,谢谢

javascript arrays angular typescript indexof
1个回答
0
投票

我在这里为您解决了问题

var array1 = [{ name: "num", features: ['id', 'gender']},
            { name: "cat", features: ['gender']}];
ob = {name:'num2', features:['id']};

function updateArr(arr, ob){
  for(var i = 0;i < arr.length; i++) {
    if(ob.features.join("") === arr[i].features.join("")) {
      arr[i] = ob;
      return;
    }
  }
  arr.push(ob);
}

/* you are changing the array, so if you print the array
 before you will get the result of after because it's a
 reference and not literal :)*/
updateArr(array1, ob);
console.log(array1);

0
投票

您可以简单地在下面的代码行中更改比较运算符

ob.features.toString() === x.features.toString()

to

JSON.stringify(ob.features.sort()) === JSON.stringify(x.features.sort())

如果不想使用stringify,则可以使用答案中提到的数组比较功能-https://stackoverflow.com/a/16436975/989139


0
投票

let array1 = [{ name: "num", features: ['id']  },
            { name: "cat", features: ['gender'] }];
ob = {name:'num2', features:['id']};

function updateArr(arr,ob){

  const index = arr.findIndex(x => 
  ob.features.includes(x.features)
     // ob.features.toString() === x.features.toString()
                              );
                              debugger
    if (index === -1) {
        arr.push(ob);
    } else {
        arr[index] = ob;
    }
}
console.log(array1);
updateArr(array1,ob);
console.log(array1);
© www.soinside.com 2019 - 2024. All rights reserved.