findIndex的替代方案,用于导航和编辑多层对象数组

时间:2018-01-22 16:58:44

标签: javascript json node.js

我有一个看起来像这样的对象:

{
userId: 111,
notes: [
    {
      name: 'Collection1',
      categories: [
        {
          name: 'Category1',
          notes: [
            {data: 'This is the first note', id: '1238123-12931'}
          ]
        }
      ]
    }
  ]
}

在Mongoose中,我需要推送/删除/编辑笔记。对于推送,我需要使用集合名称和类别名称导航到我想要的对象中的注释。对于编辑或删除,我需要那些加上注释ID。然后我需要通过push / splice / reassign来改变来自mongoose的原始对象来完成我的任务。到目前为止我做的方式是这样的:

var collectionIndex = obj.notes.findIndex(collection => collection.name === query.collection)
if (collectionIndex === -1) return console.log('Collection not found')
var categoryIndex = obj.notes.[collectionIndex].categories.findIndex(category => category.name === query.category)
if (categoryIndex === -1) return console.log('Category not found')

obj.notes[collectionIndex].categories[categoryIndex].notes.push(newNote)

这种方法看起来非常冗长,而且我很想知道是否有更好的方法可以用更少的代码来完成相同的结果。

1 个答案:

答案 0 :(得分:0)

稍短一些:

var collection = obj.notes.find(x => x.name == query.collection && x.categories.some(y => y.name == query.category));
!!collection && collection.categories.find(x => x.name == query.category).notes.push(newNote);
相关问题