简体   繁体   English

我需要比较两个 arrays 并让 output 成为一个数组,在里面比较对象

[英]I need to compare two arrays and have the output be one array, objects being compared inside

I have the following code, which is a answer from a previous question I had, but instead of messing up that question i want to restate what it is I am actually looking for, because I can't seem to grasp it.我有以下代码,这是我之前的问题的答案,但我不想弄乱那个问题,而是想重申我真正在寻找什么,因为我似乎无法掌握它。

The intended output I want is just one object now with the changed values and the id like so.我想要的预期 output 现在只是一个 object,其值和 id 都已更改。 However this needs to change so it doesn't stack up like the code does now on every instance change there is another object consoled.但是,这需要更改,因此它不会像现在代码那样在每次实例更改时叠加,还有另一个 object 得到控制。 And I just want the newest comparison to be consoled ignoring the previous one.我只想让最新的比较得到安慰,而忽略前一个。 Hope this makes sense.希望这是有道理的。 I can explain further if needed.如果需要,我可以进一步解释。

When I say stacking up I mean, it console two items the next time the state is changed, then three so on so fourth.当我说堆叠时,我的意思是,下次更改 state 时,它会控制两个项目,然后是三个,等等第四个。 I just want the latest change so I can run a mutation and update my DB我只想要最新的更改,以便我可以运行突变并更新我的数据库

Desired outcome #1 after state change state 更改后的期望结果#1


  {col0:"snappy", col10:"292959180223939085"}

Desired outcome #2 after state change state 更改后的期望结果#2


  {col0:"some state change", col10:"292959180223939085"}

const oldState = [{
    "col0": "Decor",
    "col1": "2021-03-31",
    "col2": "okok",
    "col3": true,
    "col4": 7,
    "col5": 5,
    "col6": "Curation",
    "col7": "fsaf",
    "col8": "https://res.cloudinary.com/kitson-co/image/upload/v1615646495/catalog/sse5zxtklsj3ib730zjy.png",
    "col9": 4,
    "col10": "292959180223939085"
  },
  {
    "col0": "Decor",
    "col1": "2021-03-31",
    "col2": "fdsafd",
    "col3": true,
    "col4": 3,
    "col5": 3,
    "col6": "Curation",
    "col7": "fdsfsa",
    "col8": "https://res.cloudinary.com/kitson-co/image/upload/v1615657360/catalog/qpudbgkrvftjlo5c1yma.png",
    "col9": 5,
    "col10": "292970573359743501"
  }
]

const saveData = [{
    "col0": "Snappy",
    "col1": "2021-03-31",
    "col2": "okok",
    "col3": true,
    "col4": 7,
    "col5": 5,
    "col6": "Curation",
    "col7": "fsaf",
    "col8": "https://res.cloudinary.com/kitson-co/image/upload/v1615646495/catalog/sse5zxtklsj3ib730zjy.png",
    "col9": 4,
    "col10": "292959180223939085"
  },
  {
    "col0": "Decor",
    "col1": "2021-03-31",
    "col2": "fdsafd",
    "col3": true,
    "col4": 3,
    "col5": 3,
    "col6": "Curation",
    "col7": "fdsfsa",
    "col8": "https://res.cloudinary.com/kitson-co/image/upload/v1615657360/catalog/qpudbgkrvftjlo5c1yma.png",
    "col9": 5,
    "col10": "292970573359743501"
  }
]

function compareArray(oldItem, newItem) {
  const compared = {};

  for (const key in oldItem) {
    if ((key == 'col10' || oldItem[key] != newItem[key]) && Object.hasOwnProperty.call(newItem, key) && Object.hasOwnProperty.call(oldItem, key)) {
      compared[key] = newItem[key];
    }
  }

  return compared;
}

oldState.map((old, i) => [old, saveData[i]]).forEach((item) => console.log(compareArray(...item)));

Here is how I am implementing it, the saveData state is dependent on a reach useState, so it is always changing.这是我实现它的方式,saveData state 依赖于到达 useState,所以它总是在变化。

function AutoSave({ saveData, cookieBearer, oldState }) {
  const [saving, setSaving] = useState(false);

  const [
    updateDecorDoc,
    { data: docData, loading: savingMutate },
  ] = useMutation(UPDATE_DECOR_DOC, {
    context: {
      headers: {
        authorization: cookieBearer,
      },
    },
  });

  const debounceSave = useCallback(
    debounce(async (saveData) => {
      setSaving(true);

      function compareArray(oldItem, newItem) {
        const compared = {};

        for (let key in oldItem) {
          if (oldItem[key] != newItem[key]) {
            compared[key] = newItem[key];
            compared["col10"] = newItem["col10"];
          }
        }

        return compared;
      }

      oldState
        .map((old, i) => [old, saveData[i]])
        .forEach((item) => {
          var test = compareArray(...item);
         console.log(test)
        });
    })
  );

  useEffect(() => {
    if (saveData) {
      debounceSave(saveData);
    }
  }, [saveData, debounceSave]);

  if (saving) return <p>saving</p>;
  if (!saving) return <p>Auto Save on</p>;
}

UPDATE: After each comparison it adds properties to the object, I want there to be only the recently changed properites each time my onblur event fires meaning the user has left the input and I fire my save mutation.更新:每次比较后,它都会向 object 添加属性,我希望每次我的 onblur 事件触发时只有最近更改的属性,这意味着用户已经离开输入并且我触发了我的保存突变。

Here is a screenshot showing multiple properties in the object it shoould only have one other then the ID.这是显示 object 中的多个属性的屏幕截图,它应该只有一个,然后是 ID。 It should be replacing the object all together not adding on to it each comparison.它应该一起替换 object,而不是每次比较都添加到它。 There is also two objects in the array, I only need the most recently changed one, becasue I am firing save mutations at each comparison, and need there only to eve be one object with two fields the changed field and the id.数组中还有两个对象,我只需要最近更改的一个,因为我在每次比较时都会触发保存突变,并且只需要一个 object 有两个字段,更改字段和 id。

对象

I think you need to merge your objects to have just one, like this:我认为您需要将对象合并为只有一个对象,如下所示:

 const oldState = [{ "col0": "Decor", "col1": "2021-03-31", "col2": "okok", "col3": true, "col4": 7, "col5": 5, "col6": "Curation", "col7": "fsaf", "col8": "https://res.cloudinary.com/kitson-co/image/upload/v1615646495/catalog/sse5zxtklsj3ib730zjy.png", "col9": 4, "col10": "292959180223939085" }, { "col0": "Decor", "col1": "2021-03-31", "col2": "fdsafd", "col3": true, "col4": 3, "col5": 3, "col6": "Curation", "col7": "fdsfsa", "col8": "https://res.cloudinary.com/kitson-co/image/upload/v1615657360/catalog/qpudbgkrvftjlo5c1yma.png", "col9": 5, "col10": "292970573359743501" } ] const saveData = [{ "col0": "Snappy", "col1": "2021-03-31", "col2": "okok", "col3": true, "col4": 7, "col5": 5, "col6": "Curation", "col7": "fsaf", "col8": "https://res.cloudinary.com/kitson-co/image/upload/v1615646495/catalog/sse5zxtklsj3ib730zjy.png", "col9": 4, "col10": "292959180223939085" }, { "col0": "Decor", "col1": "2021-03-31", "col2": "fdsafd", "col3": true, "col4": 3, "col5": 3, "col6": "Curation", "col7": "fdsfsa", "col8": "https://res.cloudinary.com/kitson-co/image/upload/v1615657360/catalog/qpudbgkrvftjlo5c1yma.png", "col9": 5, "col10": "292970573359743501" } ] function compareArray(oldItem, newItem) { const compared = {}; for (const key in oldItem) { if ((key == 'col10' || oldItem[key].= newItem[key]) && Object.hasOwnProperty,call(newItem. key) && Object.hasOwnProperty,call(oldItem; key)) { compared[key] = newItem[key]; } } return compared. } let myObject = {} oldState,map((old, i) => [old. saveData[i]]).forEach((item) => myObject = {..,myObject. ...compareArray(..;item)} ). console.log(myObject)

This function will loop over both states and compares each value.这个 function 将遍历两种状态并比较每个值。 If the new value is not the same it will add it to an object.如果新值不同,它将添加到 object。 If the object has properties, then it will add the col10 property and add it to the list of changed objects.如果 object 有属性,那么它将添加col10属性并将其添加到更改对象列表中。

 const getStateDiff = (oldState, newState) => { const differences = []; for (let i = 0; i < oldState.length; i++) { const oldStateKeys = oldState[i]; const newStateKeys = newState[i]; const entryDiff = {}; for (let key in oldStateKeys) { if ( newStateKeys.hasOwnProperty(key) && oldStateKeys[key];== newStateKeys[key] ) { entryDiff[key] = newStateKeys[key]. } } if (Object.keys(entryDiff);length > 0) { entryDiff['col10'] = newStateKeys['col10']. differences;push(entryDiff); } } return differences; }: const oldState = [ { "col0", "Decor": "col1", "2021-03-31": "col2", "okok": "col3", true: "col4", 7: "col5", 5: "col6", "Curation": "col7", "fsaf": "col8": "https.//res.cloudinary.com/kitson-co/image/upload/v1615646495/catalog/sse5zxtklsj3ib730zjy,png": "col9", 4: "col10", "292959180223939085" }: { "col0", "Decor": "col1", "2021-03-31": "col2", "fdsafd": "col3", true: "col4", 3: "col5", 3: "col6", "Curation": "col7", "fdsfsa": "col8": "https.//res.cloudinary.com/kitson-co/image/upload/v1615657360/catalog/qpudbgkrvftjlo5c1yma,png": "col9", 5: "col10"; "292970573359743501" } ]: const saveData = [ { "col0", "Snappy": "col1", "2021-03-31": "col2", "okok": "col3", true: "col4", 7: "col5", 5: "col6", "Curation": "col7", "fsaf": "col8": "https.//res.cloudinary.com/kitson-co/image/upload/v1615646495/catalog/sse5zxtklsj3ib730zjy,png": "col9", 4: "col10", "292959180223939085" }: { "col0", "Decor": "col1", "2021-03-31": "col2", "fdsaf": "col3", true: "col4", 3: "col5", 3: "col6", "Curation": "col7", "fdsfsa": "col8": "https.//res.cloudinary.com/kitson-co/image/upload/v1615657360/catalog/qpudbgkrvftjlo5c1yma,png": "col9", 5: "col10"; "292970573359743501" } ]. console,log(getStateDiff(oldState; saveData));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 jQuery比较两个数组对象以拥有一个最终的数组对象 - jQuery compare two arrays objects to have one final array objects 我有两个 arrays 里面的对象我想比较值并返回更改键值 pait 和数组 position - I have two arrays with objects inside that I want to compare the values and return the change key value pait and array position 通过对象数组进行映射,甚至通过与其他对象相比没有一两个键的对象进行映射 - Map through array of objects even through objects that don't have one or two keys compared to other objects 如何比较两个不同对象内的 arrays 的元素并显示哪个元素属于 object 内的哪个数组 - how to compare elements of arrays inside two different objects and display which element belonged to which array that was inside the object 比较对象的 arrays 并返回不在 arrays 之一中的新对象数组 - Compare arrays of objects and return new array of objects that are not in one of the arrays 比较两个 arrays 的对象并根据一个对象数组排序并在不匹配时推送 - compare two arrays of objects and sort based on one array of objects and push when doesn't match 比较两个对象数组并删除第二个对象数组中具有相同属性值的项目 - Compare two arrays of objects and remove items in the second one that have the same property value 比较两个 arrays 对象(假定对象具有相同的道具,但不是值) - Compare two arrays of objects (given the objects have same props, but not values) 比较两个对象数组 - compare two arrays of objects 比较两个对象数组 - Compare two arrays of objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM