分享一款JS工具:st.js - 从 Object 中快速提取数据或转化成另一个 Object

本工具出处
昨晚浏览技术文章,发现了一款不错的object操作工具st.js。他的主要作用是从object中提取相关数据(可利用正则进行匹配),或制定相应的规则对object进行转化。
看文档st.js主要提供了两个方法:

  1. JSON.select()
  2. JSON.transformWith()

    二者都return this,因此可进行链式调用。

JSON.select()

用来提取数据。我们可用正则来匹配key或val.

var data = {
  "links": [
    { "remote_url": "http://localhost" },
    { "file_url": "file://documents" },
    { "remote_url": "https://blahblah.com" }
  ],
  "preview": "https://image",
  "metadata": "This is a link collection"
}
var sel = JSON.select(data, function(key, val) {
 return /https?:/.test(val);
})

我们可以查看sel的以下方法:
keys 符合条件的键的集合
values 符合条件的值的集合
paths 符合条件的键值对在data中位置的集合
root符合条件的对象

transformWith

用来转换对象

var data = {
  "title": "List of websites",
  "description": "This is a list of popular websites"
  "data": {
    "sites": [{
      "name": "Google",
      "url": "https://google.com"
    }, {
      "name": "Facebook",
      "url": "https://facebook.com"
    }, {
      "name": "Twitter",
      "url": "https://twitter.com"
    }, {
      "name": "Github",
      "url": "https://github.com"
    }]
  }
}
var sel = JSON.select(data, function(key, val){
            return key === 'sites';
          })
          .transformWith({
            "items": {
              "{{#each sites}}": {
                "tag": "<a href='{{url}}'>{{name}}</a>"
              }
            }
          })

“{{#each sites}}” 可理解为遍历sel.sites的每个子项并处理后归到items中。

使用方法

In a browser

<script src="st.js"></script>
<script>
var parsed = JSON.select({ "items": [1,2,3,4] })
                .transformWith({
                  "{{#each items}}": {
                    "type": "label", "text": "{{this}}"
                  }
                })
                .root();
</script>

In node.js

$ npm install stjs
require('st');

var parsed = JSON.select({ "items": [1,2,3,4] })
                .transformWith({
                  "{{#each items}}": {
                    "type": "label", "text": "{{this}}"
                  }
                })
                .root();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值