简体   繁体   English

如何使用双簧管迭代对象数组?

[英]How to iterate over array of objects using oboe?

I have a json response in the form of: 我有以下形式的json响应:

[{
  "id": 425055,
  "title": "Foo"
}, {
  "id": 425038,
  "title": "Bar"
}, {
  "id": 425015,
  "title": "Narf"
}]

I use oboe.js to create a highland stream: 我使用oboe.js创建高地流:

const cruiseNidStream = _((push, next) => {
    oboe({
        url: 'http://fake.com/bar/overview,
        method: 'GET',
        headers: {
            'X-AUTH': 'some token',
        },
    }).node('.*', (overview) => {
        // I expect here to get an object having and id, title property
        push(null, overview.id);
    }).done((overview) => {
        push(null, _.nil);
    }).fail((reason) => {
        console.error(reason);
        push(null, _.nil);
    });
});

My problem is that I don't know what pattern to use node so that it matches each element of that array. 我的问题是我不知道该使用哪种模式节点才能使其与该数组的每个元素匹配。 As currently the items I am getting with the current setup are all the objects and the properties again: 目前,通过当前设置获得的项目是所有对象和属性:

425055
Foo
{ id: 227709, title: 'Foo' }

If the response would have had a property like: 如果响应具有以下属性:

{
  'overview': [],
}

I could have used .overview.* . 我本可以使用.overview.*

Oboe has two ways of matching data, by path and by duck-typing. Oboe有两种通过路径和鸭子类型匹配数据的方式。

By duck-typing 通过鸭式打字

oboe('/data.json')
  .node('{id title}', function(x) {
    console.log('from duck-typing', x)
  })

By path 按路径

oboe('/data.json')
  .node('!.*', function(x) {
    console.log('from path matching', x)
  })
  //or also valid
  .node('!.[*]', function(x) {
    console.log('from path matching', x)
  })

In the path example, notice the ! 在路径示例中,请注意! character. 字符。 This refers to the root node of the tree, this pattern will only your three objects, not any of their own properties nested further down. 这是指树的根节点,此模式只会将您的三个对象,而不是将它们自己的任何属性嵌套在更下方。

I made a gomix where you can view this working in the console, and also view the source . 我制作了一个gomix ,您可以在控制台中查看它的工作情况,还可以查看源代码

Oboe.js supports duck typing: Oboe.js支持鸭子输入:

.node('{id title}', (overview) => {
 }

Note that my json was flat, so this works. 请注意,我的json是扁平的,因此可以正常工作。 You result may vary for nested json. 对于嵌套的json,结果可能会有所不同。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM