簡體   English   中英

Json數組與javascript中不同長度的比較

[英]Json Array compare with different length in javascript

如果 arr1 和 arr2 中的 id 相同,則我用於創建新數組的代碼如下。 但不起作用,因為 arr1 和 arr2 不同。 數組 1 有索引,而 arr2 沒有索引。 截圖供您參考。 有人可以幫忙嗎?

注意:arr1 中的 ID 與 arr2 中的 EmpId 相同

for(let i=0; i<arr1.length; i++) {
 merged.push({
 ...arr1[i], 
 ...(arr2.find((itmInner) => itmInner.id === arr1[i].id))}
 );
 }
 console.log(merged);

Array1 看起來像這樣:

[{"Active":1,"Id":1},
 {"Active":1,"Id":3},
 {"Active":1,"Id":2}]

Array2 看起來像這樣:

在此處輸入圖片說明

下面是關於我如何構建數組 2 的示例代碼:

renderElement(activity){
var arr2 = [] ;
for(var i = 0; i < activity.length; i++) {
obj = activity[i];
if(obj.Id == 28){
 fetch(geturl)
.then(function (response) {
return response.json();
})
.then(function (data) {
 res  = data;
 arr2.push(res)
})
}
else{
// Do nothing
}
}
return  arr2 
}

調用Render方法如下:

outputarray = currentComponent.renderElement(activity); 
console.log('output', outputarray)

預期輸出:

[{"Active":1,"Id":1,"Param1": true},
{"Active":1,"Id":3}, / Keep it as such if nothing exists in other array
{"Active":1,"Id":2, "Param2": false}]

你可以試試這個方法:

示例#1

 const arr1 = [ { "Active":1, "Id":1 }, { "Active":1, "Id":3 }, { "Active":1, "Id":2 } ]; const arr2 = [ { 0: [ { EmpId1: 1, Param1: true } ] }, { 1: [ { EmpId2: 2,Param2: false } ] }, { 2: [ { EmpId3: 2 } ] }, ]; const response = arr1 .reduce((acc, value) => { const secondaryData = arr2.map((val, index) => { const { [`EmpId${index + 1}`]: Id, ...others } = val[Object.keys(val)][0]; return { Id, ...others }; }); const match = secondaryData.findIndex(({ Id }) => Id === value.Id); if (match >= 0) acc.push({...value, ...secondaryData[match]}) else acc.push(value); return acc; }, []); console.log(response);

示例#2

 const arr1 = [ { "Active":1, "Id":1 }, { "Active":1, "Id":3 }, { "Active":1, "Id":2 } ]; const arr2 = [ [ { EmpId1: 1, Param1: true } ], [ { EmpId2: 2, Param2: false } ], [ { EmpId3: 2 } ], ] const response = arr1 .reduce((acc, value) => { const secondaryData = arr2.map(([val], index) => { const { [`EmpId${index + 1}`]: Id, ...others } = val; return { Id, ...others }; }); const match = secondaryData.findIndex(({ Id }) => Id === value.Id); if (match >= 0) acc.push({...value, ...secondaryData[match]}) else acc.push(value); return acc; }, []); console.log(response);

基本上,您可以通過對象屬性創建哈希映射,並在該屬性上連接所有數組,即將數組數組減少為結果對象,然后將對象的值轉換回數組。 由於每個數組都減少了,這意味着每個數組只遍歷一次O(n)並且 map 對象提供恆定時間O(1)查找以匹配對象。 這使解決方案更接近O(n)而不是其他具有嵌套O(n) findIndex搜索的解決方案,這會產生更接近O(n^2)的解決方案。

const mergeByField = (...arrays) => {
  return Object.values(
    arrays.reduce(
      (result, { data, field }) => ({
        ...data.flat().reduce(
          (obj, el) => ({
            ...obj,
            [el[field]]: {
              ...obj[el[field]],
              ...el
            }
          }),
          result
        )
      }),
      {}
    )
  );
};

將每個數組加載到指定要匹配的字段鍵的負載對象中。 這將返回用於匹配的所有字段,但這些字段可以在以后安全地忽略或刪除,無論您需要什么。 例子:

mergeByField(
  { data: arr1, field: "Id" },
  { data: arr2, field: "EmpId" },
);

 const arr1 = [ { Active: 1, Id: 1 }, { Active: 1, Id: 2 }, { Active: 1, Id: 3 } ]; const arr2 = [[{ EmpId: 1, Param1: true }], [{ EmpId: 3, Param2: false }]]; const mergeByField = (...arrays) => { return Object.values( arrays.reduce( (result, { data, field }) => ({ ...data.flat().reduce( (obj, el) => ({ ...obj, [el[field]]: { ...obj[el[field]], ...el } }), result ) }), {} ) ); }; console.log( mergeByField({ data: arr1, field: "Id" }, { data: arr2, field: "EmpId" }) );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM