對象扁平化



flatten(obj) {

? ? ? var result = {};

? ? ? function recurse(src, prop) {

? ? ? ? var toString = Object.prototype.toString;

? ? ? ? if (toString.call(src) == "[object Object]") {

? ? ? ? ? var isEmpty = true;

? ? ? ? ? for (var p in src) {

? ? ? ? ? ? isEmpty = false;

? ? ? ? ? ? recurse(src[p], prop ? prop + "." + p : p);

? ? ? ? ? }

? ? ? ? ? if (isEmpty && prop) {

? ? ? ? ? ? result[prop] = {};

? ? ? ? ? }

? ? ? ? } else if (toString.call(src) == "[object Array]") {

? ? ? ? ? var len = src.length;

? ? ? ? ? if (len > 0) {

? ? ? ? ? ? src.forEach(function (item, index) {

? ? ? ? ? ? ? recurse(item, prop ? prop + ".[" + index + "]" : index);

? ? ? ? ? ? });

? ? ? ? ? } else {

? ? ? ? ? ? result[prop] = [];

? ? ? ? ? }

? ? ? ? } else {

? ? ? ? ? result[prop] = src;

? ? ? ? }

? ? ? }

? ? ? recurse(obj, "");

? ? ? console.log(result, "423423");

? ? ? return result;

? ? },




調(diào)用:

this.flatten({

? ? ? a: {

? ? ? ? b: 1,

? ? ? ? c: 2,

? ? ? ? d: { e: 5 },

? ? ? },

? ? ? b: [1, 3, { a: 2, b: 3 }],

? ? ? c: 3,

? ? });

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. 函數(shù) 1.1 函數(shù)的 3 種定義方法 1.1.1 函數(shù)聲明 //ES5 functiongetSum(){}...
    Mrssssss閱讀 451評論 0 0
  • 原文鏈接JavaScript原生匯總[https://b...
    未來仍可期閱讀 774評論 0 0
  • //什么是數(shù)組扁平化 //將嵌套多層的數(shù)組,轉(zhuǎn)為一層數(shù)組叫做數(shù)組扁平化 vararr=[1,[2,[3]]] //...
    流星絕塵閱讀 296評論 0 0
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,511評論 19 139
  • 本文是在學習和使用kotlin時的一些總結(jié)與體會,一些代碼示例來自于網(wǎng)絡(luò)或Kotlin官方文檔,持續(xù)更新... 對...
    竹塵居士閱讀 3,461評論 0 8

友情鏈接更多精彩內(nèi)容