javascript通过另一个对象数组

时间:2018-07-31 21:06:21

标签: javascript arrays ecmascript-6

我想在另一个数组中添加或替换一个对象。

var arr = [
  {uid: 1, name: "bla", description: "cucu"},
  {uid: 2, name: "smth else", description: "cucarecu"},
]

这是一个新对象:

var mynewObject = {uid: 1, name: "newBlabla", description: "newDesc"};

我已经这样做了:

function addOrReplace (arr, object) {
  var index = arr.findIndex(x => object.uid === x.uid);
  if (-1 === index) {
    arr.push(object);
  } else {
    arr[index] = object;
  }
  return arr;
} 

但这很丑。 有没有办法在一两行中做到这一点?

原始数组应仍为数组,而新对象应仅由属性uid检查。

2 个答案:

答案 0 :(得分:6)

要实现相同的功能,但使其更紧凑,运行Array#findIndex并将其结果分配给函数的未使用参数idx(有效覆盖其值, (默认为undefined或调用函数的值),然后使用简单的ternary operator修改现有对象或添加到数组中,最后返回修改后的对象数组。

const arr1 = [
  { uid: 1, name: "bla", description: "cucu" },
  { uid: 2, name: "smth else", description: "cucarecu" },
]
const mynewObject1 = { uid: 1, name: "newBlabla", description: "newDesc" };

const arr2 = [
  { uid: 2, name: "smth else", description: "cucarecu" },
]
const mynewObject2 = { uid: 1, name: "newBlabla", description: "newDesc" };

const arr3 = []
const mynewObject3 = { uid: 1, name: "newBlabla", description: "newDesc" };

function addOrReplace (arr, obj, idx) {
  return (idx = arr.findIndex(x => obj.uid === x.uid) > -1 ? arr[idx] = obj : arr.push(obj)), arr;
}

console.log(addOrReplace(arr1, mynewObject1));
console.log(addOrReplace(arr2, mynewObject2));
console.log(addOrReplace(arr3, mynewObject3));

或者更简洁一些,如果您不需要返回数组:

const arr1 = [
  { uid: 1, name: "bla", description: "cucu" },
  { uid: 2, name: "smth else", description: "cucarecu" },
]
const mynewObject1 = { uid: 1, name: "newBlabla", description: "newDesc" };

const arr2 = [
  { uid: 2, name: "smth else", description: "cucarecu" },
]
const mynewObject2 = { uid: 1, name: "newBlabla", description: "newDesc" };

const arr3 = []
const mynewObject3 = { uid: 1, name: "newBlabla", description: "newDesc" };

function addOrReplace (arr, obj, idx) {
  idx = arr.findIndex(x => obj.uid === x.uid) > -1 ? arr[idx] = obj : arr.push(obj);
}

addOrReplace(arr1, mynewObject1)
console.log(arr1);

addOrReplace(arr2, mynewObject2)
console.log(arr2);

addOrReplace(arr3, mynewObject3)
console.log(arr3);

答案 1 :(得分:1)

const addOrReplace = (arr, obj) => {
    arr = arr.filter(el => el.uid !== obj.uid);
    arr.push(obj)
    return arr;
}