从JavaScript对象过滤掉键 [英] Filtering out keys from a JavaScript object

查看:73
本文介绍了从JavaScript对象过滤掉键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的JavaScript对象

I have a JavaScript object in the below format

{
"Node1": [
    {
    "Node2": "node2detail1",
    "Node3": "node3detail1",
    "Node4": [
        "node4detail1",
        ]
    },
    {
    "Node2": "node2detail2",
    "Node3": "node3detail2",
    "Node4": [
        "node4detail2",
        ]
    },
    {
    "Node2": "node2detail3",
    "Node3": "node3detail3",
    "Node4": [
        "node4detail3",
        ]
    }
]}

是否可以编写一个jsonpath表达式,该表达式将导致以下格式的JavaScript对象? 目的是按键进行过滤.

Is it possible to write an jsonpath expression which would result in a JavaScript object in the following format? The intention is to filter by keys.

{
"Node1": [
    {
    "Node2": "node2detail1",
    "Node3": "node3detail1",
    },
    {
    "Node2": "node2detail2",
    "Node3": "node3detail2",
    },
    {
    "Node2": "node2detail3",
    "Node3": "node3detail3",
    }
]}

推荐答案

Jsonpath用于提取值,而不是过滤JavaScript对象.您可以使用以下方法过滤对象:

Jsonpath is for extracting values, not filtering JavaScript objects. You can filter your object with:

{Node1: obj.Node1.map(function(o) { return {Node2: o.Node2, Node3: o.Node3}; })}

如果您想使用Underscore,则有_.pick:

If you prefer to use Underscore, there is _.pick:

{Node1: _.map(obj.Node1, function(o) { return _.pick(o, 'Node2', 'Node3'); })}

如果您要使用ES6/Harmony,请使用简化的对象文字语法将map函数定义为具有解构参数和隐式返回值的箭头函数:

If ES6/Harmony is your thing, define the map function as an arrow function with deconstructed parameters and implicit return value using simplified object literal syntax:

{Node1: obj.Node1.map(({Node2, Node3}) => ({Node2, Node3}))}

破坏性地变换:

obj.Node1.forEach(function(o) { delete o.Node4; })

如果您愿意,可以使用JSON.stringify的属性过滤功能.该数组指定要序列化为JSON字符串的键;其他人将被忽略.

If it suits your fancy, you can use the property filtering capability of JSON.stringify. The array specifies keys to be serialized into the JSON string; others are ignored.

JSON.parse(JSON.stringify(obj, ['Node1', 'Node2', 'Node3']))

或者您可以指定替换函数(带有键和值参数)并通过返回undefined来杀死Node4,这意味着跳过该键及其值:

Or you could specify a replacer function (taking key and value parameters) and kill Node4 by returningundefined which means to skip that key and its value:

JSON.parse(JSON.stringify(obj, function(k, v) { if (k !== 'Node4') return v; }))

这篇关于从JavaScript对象过滤掉键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆