简体   繁体   中英

JS -Append key to matching array, object values

I would like to push key values to objects in array1 from other objects of array2

To do so it needs to search a corresponding values in both arrays, then push the right key.

let array1 = [
  {
    "Ref": "28189-060-B",
    "Otherkey": "Whatever"
  },
  {
    "Ref": "18182-250-B",
    "Otherkey": "Whatever2"
  },
  {
    "Ref": "55187-753-B",
    "Otherkey": "Whatever3"
  }
]

let array2 = [
  {
    "Ref": "28189-060-ABCD",
    "Style": "Red"
  },
  {
    "Ref": "18182-250-ABCD",
    "Style": "Blue"
  },
  {
    "Ref": "55187-753-ABCD",
    "Style": "Yellow"
  }
]

The function need to loop through all objects in array1, look at the first 9 characters of Ref values, find a match in array2 Ref (only first 9 characters are identical). When there is a match push the "Style" from array2 into the corresponding object in array1

I tried with Object.key.foreach(), map(), with substr to get only 9 characters, with find()... all of this has been a big mess and not working...

Expected result :

let array1 = [
    {
    "Ref": "18182-250-B",
    "Otherkey": "Whatever2",
    "Style": "Blue"
  },
{
    "Ref": "28189-060-B",
    "Otherkey": "Whatever",
    "Style": "Red"
  },
  {
    "Ref": "55187-753-B",
    "Otherkey": "Whatever3",
    "Style": "Yellow"
  }
]

Assuming those properties are all meant to be Ref (some are Global_Style ), you can use forEach and find :

 let array1 = [{"Ref":"28189-060-B","Otherkey":"Whatever"},{"Ref":"18182-250-B","Otherkey":"Whatever2"},{"Ref":"55187-753-B","Otherkey":"Whatever3"}]; let array2 = [{"Ref":"28189-060-ABCD","Style":"Red"},{"Ref":"18182-250-ABCD","Style":"Blue"},{"Ref":"55187-753-ABCD","Style":"Yellow"}]; const shorterRef = (ref) => ref.substr(0, 9); array1.forEach(obj => { const a1Ref = shorterRef(obj.Ref); const arr2Obj = array2.find(tmp => shorterRef(tmp.Ref) === a1Ref); if (arr2Obj) obj.Style = arr2Obj.Style; }); console.log(array1); 

If you didn't want to mutate the array go with map :

 let array1 = [{"Ref":"28189-060-B","Otherkey":"Whatever"},{"Ref":"18182-250-B","Otherkey":"Whatever2"},{"Ref":"55187-753-B","Otherkey":"Whatever3"}]; let array2 = [{"Ref":"28189-060-ABCD","Style":"Red"},{"Ref":"18182-250-ABCD","Style":"Blue"},{"Ref":"55187-753-ABCD","Style":"Yellow"}]; const shorterRef = (ref) => ref.substr(0, 9); const out = array1.map(obj => { const a1Ref = shorterRef(obj.Ref); const arr2Obj = array2.find(tmp => shorterRef(tmp.Ref) === a1Ref); if (arr2Obj) return { ...obj, Style: arr2Obj.Style }; }); console.log(out); 

var arrMap = {};
array1.forEach(function(x){
    if(!arrMap[x.Ref.substring(0,9)]){
        arrMap[x.Ref.substring(0,9)] = x;
    }
});

array2.forEach(function(x){
 if(Object.keys(arrMap).includes(x.Ref.substring(0,9))){
        arrMap[x.Ref.substring(0,9)] = Object.assign(arrMap[x.Ref.substring(0,9)], {"Style": x.Style});
    }
});
console.log(Object.values(arrMap));

Something like this may be what you want:

array1.forEach(function (element1) {
    array2.forEach(function (element2){
        addStyle(element1, element2);        
    });
});

function addStyle(obj1, obj2){
    if (obj1.Ref && obj2.Ref){
        let Ref1 = obj1.Ref.substr(0,8);
        let Ref2 = obj2.Ref.substr(0, 8);
        if (Ref1 === Ref2){
            obj1.Style = obj2.Style;
        };
    }
 }

So we loop through the fist array and for each item we loop through the second array.

Then we check if the expected fields are present and if so we compare them. If they match we add the "Style" field and move to the next object

The Below code will work although we might be able to optimize it further.

var newArr = []

for(let k in array1){
  for(let i in array2){
    console.log(array2[i]['Ref'].substr(0,9))

      if(array1[k]['Ref'].substr(0,9) == array2[i]['Ref'].substr(0,9)){
          let temp = array1[k]
          temp['Style'] = array2[i]['Style']
          newArr.push(temp)
      }
  }
}

The first solution is a bit complex. You probable have a typo in array1 as your first key is not consistent. instead of Global_Stylecode you probably meant Ref , Anyway most likely it should have the same key. If we assume that the key is Ref, then

    array1.forEach( ({Ref: Ref1, Otherkey}, index) => {
      const Ref1Sub = Ref1.substring(0, 9);
      array2.forEach(({Ref: Ref2, Style}) => {
        if (Ref2.includes(Ref1Sub)) {
          array1[index].Style = Style;
        }
      })
    });

Also there is no need to define arrays as let . const will be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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