如何将JSON对象结构转换为点表示法? [英] How to convert JSON object structure to dot notation?

查看:170
本文介绍了如何将JSON对象结构转换为点表示法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我正在存储的变量,它将决定从查询中排除哪些字段:

I've got a variable I'm storing that will dictate what fields to exclude from a query:

excludeFields = {
  Contact: {
    Address: 0,
    Phone: 0
  }
}

我需要将其转换为可与Mongo的 findOne 一起使用的点符号,例如:

I need to convert this to a dot notation that will work with Mongo's findOne, e.g.:

things.findOne({}, {fields: {'Contact.Address': 0, 'Contact.Phone': 0}})

只是传递 excludeFields 不起作用并导致错误, 投影值应为1,0,true或false之一

Just passing excludeFields does not work and results in an error, "Projection values should be one of 1, 0, true, or false"

things.findOne({}, {fields: excludeFields})

我是否必须编写自己的函数来从层次结构转换为平点符号?或者是否有一些机制在我不知道的JavaScript中执行此操作?

Do I have to write my own function to convert from hierarchical structure to flat dot notation? Or is there some mechanism to do this in JavaScript that I'm not aware of?

推荐答案

这对于大多数人来说应该足够灵活需要:

This should be flexible enough for most needs:

function dotNotate(obj,target,prefix) {
  target = target || {},
  prefix = prefix || "";

  Object.keys(obj).forEach(function(key) {
    if ( typeof(obj[key]) === "object" ) {
      dotNotate(obj[key],target,prefix + key + ".");
    } else {
      return target[prefix + key] = obj[key];
    }
  });

  return target;
}

上运行excludesFields 变量如下:

dotNotate(excludeFields);

它返回当前结构:

{ "Contact.Address" : 0, "Contact.Phone" : 0 }

所以你甚至可以这样做,内联:

So you can even do, inline:

things.findOne({}, {fields: dotNotate(excludeFields) })

或作为预测提供:

var projection = { "fields": {} };
dotNotate(excludeFields,projection.fields);
things.findOne({}, projection);

除非你需要像<$这样的运算符,否则在所有深度都能很好地工作,甚至可以使用数组。 c $ c> $ push 。

这篇关于如何将JSON对象结构转换为点表示法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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