简体   繁体   English

在JSON对象中选择值

[英]Pick values inside the JSON object

In my application, I am reading the dict of keys user is interested in then returning just those in the reply object. 在我的应用程序中,我正在阅读用户感兴趣的键的字典,然后仅返回那些在答复对象中的键。 User can specify different key name. 用户可以指定其他密钥名称。

My solution works when I just pass JSON object. 当我仅传递JSON对象时,我的解决方案就可以工作。

     import * as _ from 'lodash';

     originalData = {
        "Cat" : "Cat Value",
        "Dog" : "Dog Value",
        "Rat" : "Rat Value"
     }

      transformMap = {
         "Cat" : "catData",
         "Dog" : "DogData"
      }

      let reply: any = {}
      let Keys = _.keys(transformMap)

      // Extract only the keys user wants.
      let filter = _.pick(originalData , Keys );
      if(!_.isEmpty(filter )) {
         Object.keys(filter).forEach(function (key) {
           reply[transformMap[key]] = originalData[key];
         });
      }    

For this the output is - 为此,输出为-

   reply= {
        "catData" : "Cat Value",
        "DogData" : "Dog Value"
     }

The above code works but I want to apply similar functionality when the original data is of type array - 上面的代码有效,但是当原始数据为array类型时,我想应用类似的功能-

    originalData = [
        {
          "Cat" : "Cat Value1",
          "Dog" : "Dog Value1",
          "Rat" : "Rat Value1"
        },
        {
           "Cat" : "Cat Value2",
           "Dog" : "Dog Value2",
           "Rat" : "Rat Value2"
        }
     ]

    reply= [
        {
          "catData" : "Cat Value1",
          "DogData" : "Dog Value1"
        },
        {
          "catData" : "Cat Value2",
          "DogData" : "Dog Value2"
        }
    ]

Is there a way I can achieve result for both types of output? 有两种方法都能获得结果吗?

Package up your "key transformer" into a function. 将“密钥转换器”打包成一个函数。 Then wrap it in something with flexible inputs. 然后用灵活的输入将其包装。

function transformAnything(data, tranformMap) {
  const usingArray = data instanceof Array;

  const arrayData = usingArray ? data : [data];

  const transformedData = arrayData.map(
    objectData => tranformObjectData(objectData, tranformMap)
  );

  return usingArray ? transformedData : transformedData[0];
}

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

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