在react中使用jscalpel使对象操作更容易

#1

以前

const data = {
      status: '0',
      test: {
           article: [{
                    id: 1,
                    content: 'article'
               }]
      }
}
// 要获取article的值
if (data.test && data.test.article) {
  const article = data.test.article;
  if (Array.isArray(article)) {
      // do something
  }
}

之后

jscalpel({
    target: data,
    keys: 'data.test.article',
    callback: function (article) {
      if (Array.isArray(article)) {
           console.log('article', article);
      }
    }
});

在react中的使用

import React, { Component } from 'react';
import Jscalpel from 'jscalpel'
class JscalpelCom extends Component {
    constructor(props) {
        super(props);
        this.state = {
            status: 0,
            test: {
                article: [{
                    id: 1,
                    content: 'article'
                }]
            }
        };
        this.toggleStatus = this.toggleStatus.bind(this);
    }
    toggleStatus() {
        Jscalpel({
            target: this.state,
            deep: true,
            keys: 'status',
            callback: (status) => {
                this.setState({
                    status: status ? 1 : 0
                })
            }
        })
    }
    render() {
        const { status, test } = this.state;
        const articles = Jscalpel({
            target: test,
            deep: true,
            keys: ['test.article'],
            callback: (article) => {
                if (Array.isArray(articles)) {
                    return articles.map((article, index) => {
                        return <div key={article.id}>{article.content}</div>
                    })
                }
            }
        })
        return (
            <div className="jscalpel" onClick={this.toggleStatus}>
               {status ? articles : null}
            </div>
        );
    }
}
#2

这个库在完善中,欢迎大家star提建议,对象操作在数据驱动界面开发中非常普遍