在JSON对象中选择值

时间:2019-09-12 18:50:17

标签: javascript angular typescript lodash

在我的应用程序中,我正在阅读用户感兴趣的键的字典,然后仅返回回复对象中的键。用户可以指定其他密钥名称。

当我仅传递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];
         });
      }    

为此,输出为-

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

上面的代码有效,但是当原始数据为数组类型时,我想应用类似的功能-

    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"
        }
    ]

有两种方法都能获得结果吗?

1 个答案:

答案 0 :(得分:0)

将“密钥转换器”打包成一个函数。然后用灵活的输入将其包裹起来。

property playlistToUpdate : "Public News Service"

on run -- applet or from the Script Editor
    doStuff for (choose file with multiple selections allowed)
end run

on open droppedItems -- droplet
    doStuff for droppedItems
end open

on adding folder items to theFolder after receiving theNewItems -- folder action
    doStuff for theNewItems
end adding folder items to

to doStuff for someItems -- the main stuff
    set filesAdded to {}
    repeat with anItem in someItems
        tell application "iTunes"
            launch
            delay 2
            display dialog (anItem as text)
            add anItem to playlist playlistToUpdate
        end tell
    end repeat
end doStuff