【问题标题】:How to find index nested object within array in JavaScript如何在 JavaScript 中的数组中查找索引嵌套对象
【发布时间】:2022-01-12 08:06:32
【问题描述】:

我有一个带有嵌套对象的 JS 数组作为“任务列表”。它们每个都添加了不同的紧急属性。现在我的函数需要找到最高的紧急值 - 将其设置为一个变量,然后将其从数组中删除。

我被困在从原始数组中删除它。我遇到的麻烦可能只是找到索引:

function newTask() {

  // reducing the "task list" to just the highest urgency
  let maxObj = taskList.reduce((max, obj) => (max.stockUrgency > obj.stockUrgency) ? max : obj);
  
  outputNewtask = JSON.stringify(maxObj, null, 4); 
 
 let index = taskList.indexOf("outputNewtask")
 
 console.log(index)

【问题讨论】:

  • 你的taskList怎么样?
  • 这能回答你的问题吗? How can I remove a specific item from an array?
  • 你可以分享taskList的例子吗?另请注意,outputNewtask 将是一个 JSON 字符串不是对象taskList 极不可能包含具有该确切字符串的条目。

标签: javascript arrays object reduce


【解决方案1】:

这段代码应该可以解决你的问题

const highestUrgencyValue = Math.max(...taskList.map(t => t.stockUrgency));
const highestUrgencyIndex = taskList.findIndex(task => task.stockUrgency === highestUrgencyValue);
taskList.splice(highestUrgencyIndex, 1);

【讨论】:

    【解决方案2】:

    如果您的reduce 工作正常,那么您可以使用该对象查找索引并使用splice 从列表中删除它:

        let maxObj = taskList.reduce((max, obj) => (max.stockUrgency > obj.stockUrgency) ? max : obj);
    
        taskList.splice(taskList.indexOf(maxObj), 1);
    
        outputNewtask = JSON.stringify(maxObj, null, 4); 
    

    【讨论】:

      猜你喜欢
      • 2021-11-30
      • 1970-01-01
      • 2018-01-02
      • 2021-10-04
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多