【问题标题】:JSON Array not loading completely?JSON 数组未完全加载?
【发布时间】:2019-12-21 05:50:11
【问题描述】:

我最近在尝试过滤数组时遇到了一个错误,但有时当我记录整个数组(在任何过滤之前)时,数组会丢失项目。当我多次调用此函数时会发生这种情况,是否有解决方法?

这是过滤数组的代码,我按照建议使用了 .find() 但原始数据仍在被覆盖:

let newData = dataCorte
// Log variables 
console.log('Type:',args.tipo);
// Log the WHOLE ARRAY, it has two items ALWAYS
console.log('Original Data:', dataCorte.e);
// Filter the array into a new variable
let found = newData.e.find(item => {
                return item.id === args.tipo
            })
// Log the WHOLE ARRAY, it has two items ALWAYS
 console.log('Original Data:', dataCorte.e);
// Assign the found object into the 'e' array
 newData.e = [found]

console.log('================================');
// Return the new data
return newData

【问题讨论】:

    标签: javascript graphql apollo


    【解决方案1】:

    我发现这解决了MEDZ 指出的问题,我发现here

    // Create a copy of dataCorte
    let newData = Object.assign({}, dataCorte)
     // Log variables 
    console.log('Type:',args.tipo);
    // Log the WHOLE ARRAY, it has two items ALWAYS
    console.log('Original Data:', dataCorte.e.slice());
    // Filter the array into a new variable
    console.log('Filtering for item');
    
    let found = dataCorte.e.find(item => {
                    return item.id === args.tipo
                })
    // Log the WHOLE ARRAY, it has two items ALWAYS
    console.log('Original Data:', dataCorte.e);
     // Assign the found object into the 'e' array
    newData.e = [found]
    
    console.log('================================');
    // Return the new data
    return newData
    

    【讨论】:

      【解决方案2】:

      你使用 .filter() 来获取一个值,而你应该使用 .find():

      let data = dataCorte.e.find(item => {
        return item.id === args.tipo
      }); //no need to use [0] since it will return one object
      

      这会更安全,因为您已经获取了一个值并且它不会弄乱您的数组。

      当您将dataCorte 分配给newData 时,它是通过引用而不是通过值分配的,这意味着两者都指向内存中的同一位置。为了解决这个问题,你需要解决这个问题来复制数组而不是通过引用传递它:

      // "Spread"
      let newData = { ...dataCorte }
      
      
      // "Object.assign"
      let newData = Object.assign({}, dataCorte)
      
      
      // "JSON"
      let newData = JSON.parse(JSON.stringify(dataCorte))
      

      【讨论】:

      • 刚做了,原来的数组还在修改中 D:
      • @Jeremy 我已经更新了我的答案,包括如何在代码开头解决这个任务。
      • 我正在尝试修改原始对象内的数组,然后返回整个对象。我已经尝试过:let newData = dataCorte.e.slice() 但它不起作用,因为我需要使用数组访问属性并对其进行过滤
      • 我想你没有明白我的意思。当您稍后分配newData.e = [found] 时,它也会影响dataCorte,因此如果您可以在没有事先分配的情况下return [found],那么这将解决问题。
      • 啊。我懂了。我很困惑地认为dataCorte 是一个数组,而它实际上是一个对象。检查此链接以克隆对象:samanthaming.com/tidbits/70-3-ways-to-clone-objects
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 2014-03-25
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多