[英]How to transform an array into a subset using only jsonpath?
I'd like to use jsonpath
to transform an array with 3 elements to just 2 elements. 我想使用
jsonpath
将具有3个元素的数组转换为仅2个元素。
Given this object: 给定此对象:
var _base = {
myArray: [{ item: 1, value: "first" }, { item: 2, value: "second" }, { item: 3, value: "third" }]
}
I'd like to use jsonpath-object transform
to transform the object into: 我想使用
jsonpath-object transform
transform将对象转换为:
var _newBase = {
myArray: [{ newItem: 2, newValue: "second" }, { newItem: 3, newValue: "third" }]
}
I understand I could do this with a simple slice
call and some object manipulation, but I have complex, variable objects that I'm transforming at runtime, so jsonpath
is the requirement. 我知道我可以通过一个简单的
slice
调用和一些对象操作来做到这一点,但是我有一些复杂的,可变的对象,我会在运行时进行转换,因此需要jsonpath
。
I'm able to use the below: 我可以使用以下内容:
var transform = require('jsonpath-object-transform');
var template = { ["$.myArray", { "newItem": "$..item", "newValue": "$..value" }] }
transform(_base, _template) //emits the below
Which emits: 发出:
[{ newItem: 1, newValue: "one" }, { newItem: 2, newValue: "second" }, { newItem: 3, newValue: "third" }]
But what I really need is the above object without its first index (so just the last two objects in the array). 但是我真正需要的是上面的对象没有它的第一个索引(所以只有数组中的最后两个对象)。
You can use the @path syntax to ignore the first item: 您可以使用@path语法忽略第一项:
var _template = {
foo: ['$.myArray[?(@path !== "$[\'myArray\'][0]")]']
};
Returns: 返回:
{ foo: [ { item: 2, value: 'second' }, { item: 3, value: 'third' } ] }
However, it seems that jsonpath-object transform currently doesn't support mixing both @path
and accessing subfields like in {["$.data", {"key": "$.value"}]}
. 但是,似乎jsonpath-object转换当前不支持混合
@path
和访问{["$.data", {"key": "$.value"}]}
子字段。 So this leaves you with the following options: 因此,您可以使用以下选项:
slice
-ing your objects beforehand, as you suggested. slice
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.