更新数组值的选择

时间:2018-04-21 19:03:26

标签: javascript

我有两个数组。每个数组可以具有不同数量的对象,但它们各自具有相同的属性,但可以具有不同的值。例如

var Array1 = [ { id: '1', value: a },
               { id: '2', value: b } ]

var Array2 = [ { id: '',  value: c },
               { id: '',  value: d },
               { id: '',  value: a } ]

我想要什么

AfterArray = [ { id: '1', value: a },
               { id: '3', value: c },
               { id: '4', value: d } ]

发生的事情是如果array1的对象没有array2的值,它将被删除。如果它确实有array2的值,它将保留原始id。如果对象在array2中不在array1中,则将生成一个id(UUID)。

我假设它可能会像这样

afterArray = []

this.Array1.forEach((res, i) => {
    this.Array2.forEach((res2, 2) => {
       if(res.value == res2.value){
           afterArray = afterArray.concat(this.Array1[i])
        }
        else {
        // do something if values are not present then add to array.
        // if added, add id to those empty properties. 
        }
    })
})

谢谢!

3 个答案:

答案 0 :(得分:1)

你只需要对其中有find的Array2进行简单的const array1 = [ { id: '1', value: 'a' }, { id: '2', value: 'b' } ]; const array2 = [ { id: '', value: 'c' }, { id: '', value: 'd' }, { id: '', value: 'a' } ]; const generateId = (() => { // example generator function, use your own instead let possibleIds = ['3', '4']; let i = -1; return () => { i++; return possibleIds[i]; }; })(); const result = array2.map(({ id, value }) => { // find a matching value in array1 to merge the id: const foundArr1Item = array1.find(({ value: ar1Val }) => ar1Val === value); // otherwise, generate a new ID: if (foundArr1Item) return { value, id: foundArr1Item.id }; return { value, id: generateId() }; }); console.log(result); ping操作,以查找Array1中匹配的值(如果存在):



pre-process




答案 1 :(得分:1)

如果我理解正确,这应该做你的工作: (找到代码中的注释)

Array1 = [

  {
    id: '1',
    value: "a"
  },
  {
    id: '2',
    value: "b"
  }
]

Array2 = [

  {
    id: '',
    value: "c"
  },
  {
    id: '',
    value: "d"
  },
  {
    id: '',
    value: "a"
  }
]

// keep Array1's objects if it has a value matching a value from any Array2 object 
// Also remove those objects from Array2
newArray1 = Array1.reduce((acc, elem) => {
  let indexOfObInArray2 = Array2.findIndex(eachArray2Elem => {
    return elem.value == eachArray2Elem.value
  });
  if (indexOfObInArray2 > -1) {
    acc.push(elem);
    Array2.splice(indexOfObInArray2, 1);
  }
  return acc;
}, [])

// Array of ids already taken by Objects from Array2, if they are non empty
idsTakenInArray2 = Array2.reduce((acc, x) => {
  if (x.id != "") {
    acc.push(x.id);
  }
  return acc;
}, []);

// random number to give ids
randomId = 1;
Array2 = Array2.map(eachElem => {
  if (eachElem.id == '') {
    while (Array1.find(eachArray1Elem => {
        return eachArray1Elem.id == randomId
      }) || idsTakenInArray2.indexOf(randomId) !== -1) {
      randomId++;
    }
    eachElem.id = randomId;
    idsTakenInArray2.push(randomId);;
  }
  return eachElem;
})

console.log(newArray1.concat(Array2));

答案 2 :(得分:0)

检查一下,这是在线代码https://stackblitz.com/edit/angular-zhzuqk,检查你的控制台,你会看到你想要的结果

  formtarrays(array1,array2) {
    let ar = array1.concat(array2);
    // delete items that exist in array1 but not in array2
    ar = ar.filter((elem) => {
     return !(array1.findIndex(item => item.value === elem.value) !== -1 && array2.findIndex(item => item.value === elem.value) === -1)
    })
  // get distinct values
  const idList = [];
  const distinct = [];
  ar.forEach((item, index) => {
  if (item !== undefined) {
            idList['id'] = item.value;
            if (idList.indexOf(item.value) < 0) {
                if(item.id === '') {
                  item.id = (index + array1.length).toString();
                }
                distinct.push(item);
                idList.push(item.value);
            }
      } 
  })

  console.log(distinct);
  return distinct;
 }