Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js扁平化对象,并输出 #12

Open
liucaieson opened this issue Apr 27, 2021 · 0 comments
Open

js扁平化对象,并输出 #12

liucaieson opened this issue Apr 27, 2021 · 0 comments
Labels

Comments

@liucaieson
Copy link
Owner

liucaieson commented Apr 27, 2021

项目由vue转为react
vue的国际化库和react国际化库不一样,使用的国际化文件格式不一致
vue-i18n是这样的

const language = {
  message: {
    // 新公告
    announcements: {
      announcements: '公告',
      important: '重要',
      personal: '个人',
      general: '一般',
      zh: 'Chinese',
      en: 'English',
      ...
    },
}
}

react-intl 需要这样

"announcements.announcements": "公告",
  "announcements.important": "重要",
  "announcements.personal": "个人",
  "announcements.general": "一般",
  "announcements.zh": "Chinese",
  "announcements.en": "English",
  "announcements.viewAll": "查看所有",
  "announcements.all": "全部",
  "announcements.today": "今日",

肯定不能一点点替换呀,这就是对象扁平化,用递归

// 判断对象
const isPlainObject = obj => Object.prototype.toString.call(obj) === '[object Object]'

function flatObj(entryObj) {
    //输出对象
    let outputObj = {}
    _fn(entryObj)
    return outputObj

    function _fn(obj, temp_key = '') {
	for (let key of obj) {
	    if (isPlainObject(obj[key])) {
		fn(obj[key], temp_key + key + '.')
	    } else {
		outputObj[temp_key + key] = obj[key]
	    }
	}
    }
}

就能生成这样的对象了。
因为是文件操作,我们不需要把转换完的拷贝到react项目进来。
直接在console里面打是这样的
image
这种复制出来是没有双引号的,在js文件中会报错。
采用CHORME浏览器提供的copy方法。就能直接从copy出来了。

@liucaieson liucaieson changed the title 扁平化对象,并输出 js扁平化对象,并输出 Apr 27, 2021
@liucaieson liucaieson added the JS label Apr 27, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant