如何将菊花链/点符号中的JavaScript对象展开为具有嵌套对象和数组的对象?

tjvv9vkg  于 2023-04-04  发布在  Java
关注(0)|答案(6)|浏览(118)

我想把这样的物体展平。。

var obj2 = {
    "firstName": "John",
    "lastName": "Green",
    "car.make": "Honda",
    "car.model": "Civic",
    "car.revisions.0.miles": 10150,
    "car.revisions.0.code": "REV01",
    "car.revisions.0.changes": "",
    "car.revisions.1.miles": 20021,
    "car.revisions.1.code": "REV02",
    "car.revisions.1.changes.0.type": "asthetic",
    "car.revisions.1.changes.0.desc": "Left tire cap",
    "car.revisions.1.changes.1.type": "mechanic",
    "car.revisions.1.changes.1.desc": "Engine pressure regulator",
    "visits.0.date": "2015-01-01",
    "visits.0.dealer": "DEAL-001",
    "visits.1.date": "2015-03-01",
    "visits.1.dealer": "DEAL-002"
};

...转换为一个包含嵌套对象和数组的对象,如下所示:

{
  firstName: 'John',
  lastName: 'Green',
  car: {
    make: 'Honda',
    model: 'Civic',
    revisions: [
      { miles: 10150, code: 'REV01', changes: ''},
      { miles: 20021, code: 'REV02', changes: [
        { type: 'asthetic', desc: 'Left tire cap' },
        { type: 'mechanic', desc: 'Engine pressure regulator' }
      ] }
    ]
  },
  visits: [
    { date: '2015-01-01', dealer: 'DEAL-001' },
    { date: '2015-03-01', dealer: 'DEAL-002' }
  ]
}

以下是我失败的尝试:

function unflatten(obj) {
    var result = {};

    for (var property in obj) {
        if (property.indexOf('.') > -1) {
            var substrings = property.split('.');

            console.log(substrings[0], substrings[1]);

        } else {
            result[property] = obj[property];
        }
    }

    return result;
};

我很快就开始不必要地重复代码,以便进行对象和数组的嵌套。这绝对是需要递归的东西。有什么想法吗?
编辑:我也问了相反的问题,flatten,在another question中。

zpqajqem

zpqajqem1#

你可以先使用for...in循环来循环对象属性,然后在.处拆分每个键,然后使用reduce来构建嵌套属性。

var obj2 = {"firstName":"John","lastName":"Green","car.make":"Honda","car.model":"Civic","car.revisions.0.miles":10150,"car.revisions.0.code":"REV01","car.revisions.0.changes":"","car.revisions.1.miles":20021,"car.revisions.1.code":"REV02","car.revisions.1.changes.0.type":"asthetic","car.revisions.1.changes.0.desc":"Left tire cap","car.revisions.1.changes.1.type":"mechanic","car.revisions.1.changes.1.desc":"Engine pressure regulator","visits.0.date":"2015-01-01","visits.0.dealer":"DEAL-001","visits.1.date":"2015-03-01","visits.1.dealer":"DEAL-002"}

function unflatten(data) {
  var result = {}
  for (var i in data) {
    var keys = i.split('.')
    keys.reduce(function(r, e, j) {
      return r[e] || (r[e] = isNaN(Number(keys[j + 1])) ? (keys.length - 1 == j ? data[i] : {}) : [])
    }, result)
  }
  return result
}

console.log(unflatten(obj2))
t5fffqht

t5fffqht2#

尝试将问题分解为两个不同的挑战:
1.按路径设置值
1.在对象上循环并逐个展开关键点
你可以从一个setIn函数开始,它看起来像这样:

function setIn(path, object, value) {
  let [key, ...keys] = path; 

  if (keys.length === 0) {
    object[key] = value;
  } else {
    let nextKey = keys[0];
    object[key] = object[key] || isNaN(nextKey) ? {} : [];
    setIn(keys, object[key], value);
  }

  return object;
}

然后将其与unflatten函数结合,该函数循环遍历为每个键运行setIn的对象。

function unflatten(flattened) {
  let object = {};

  for (let key in flattened) {
    let path = key.split('.');
    setIn(path, object, flattened[key]);
  }

  return object;
}

当然,已经有一个npm package来实现这个功能,而且你也可以很容易地使用lodash的_.set等函数来实现自己的功能。
你不太可能会遇到一个足够长的路径,以至于你最终会耗尽堆栈帧,但是当然也可以使用循环或trampolines来实现setIn而不使用递归。
最后,如果你喜欢不可变的数据,并且你想使用一个不修改你的数据结构的setIn版本,那么你可以看看Zaphod中的实现--一个JavaScript库,用于将原生数据结构视为不可变的。

oymdgrw7

oymdgrw73#

您可以使用lodash库与键和设置函数来构建更清晰的代码。
这个想法是,您可以使用.set转换对象中的每个条目,并将其合并到全局对象中。

const messages = {
        "firstName": "John",
        "lastName": "Green",
        "car.make": "Honda",
        "car.model": "Civic",
        "car.revisions.0.miles": 10150,
        "car.revisions.0.code": "REV01",
        "car.revisions.0.changes": "",
        "car.revisions.1.miles": 20021,
        "car.revisions.1.code": "REV02",
        "car.revisions.1.changes.0.type": "asthetic",
        "car.revisions.1.changes.0.desc": "Left tire cap",
        "car.revisions.1.changes.1.type": "mechanic",
        "car.revisions.1.changes.1.desc": "Engine pressure regulator",
        "visits.0.date": "2015-01-01",
        "visits.0.dealer": "DEAL-001",
        "visits.1.date": "2015-03-01",
        "visits.1.dealer": "DEAL-002"
};

const unflatten = (flattedObject) => {
    let result = {}
    _.keys(flattedObject).forEach(function (key, value){    
        _.set(result, key, flattedObject[key])        
    })
    return result
}

console.log(unflatten(messages))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
py49o6xq

py49o6xq4#

你可以遍历拆分后的substrings和一个临时对象,检查键是否存在,然后构建一个新的属性,检查下一个属性是否是有限数,然后分配一个数组,否则分配一个对象。最后用最后一个子字符串将值分配给临时对象。

function unflatten(obj) {
    var result = {}, temp, substrings, property, i;
    for (property in obj) {
        substrings = property.split('.');
        temp = result;
        for (i = 0; i < substrings.length - 1; i++) {
            if (!(substrings[i] in temp)) {
                if (isFinite(substrings[i + 1])) { // check if the next key is
                    temp[substrings[i]] = [];      // an index of an array
                } else {
                    temp[substrings[i]] = {};      // or a key of an object
                }
            }
            temp = temp[substrings[i]];
        }
        temp[substrings[substrings.length - 1]] = obj[property];
    }
    return result;
};

var obj2 = { "firstName": "John", "lastName": "Green", "car.make": "Honda", "car.model": "Civic", "car.revisions.0.miles": 10150, "car.revisions.0.code": "REV01", "car.revisions.0.changes": "", "car.revisions.1.miles": 20021, "car.revisions.1.code": "REV02", "car.revisions.1.changes.0.type": "asthetic", "car.revisions.1.changes.0.desc": "Left tire cap", "car.revisions.1.changes.1.type": "mechanic", "car.revisions.1.changes.1.desc": "Engine pressure regulator", "visits.0.date": "2015-01-01", "visits.0.dealer": "DEAL-001", "visits.1.date": "2015-03-01", "visits.1.dealer": "DEAL-002" };

console.log(unflatten(obj2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

稍微更紧凑的版本可能是这样的
一个二个一个一个

cgvd09ve

cgvd09ve5#

const data = {
  firstName: 'John',
  lastName: 'Green',
  'car.make': 'Honda',
  'car.model': 'Civic',
  'car.revisions.0.miles': 10150,
  'car.revisions.0.code': 'REV01',
  'car.revisions.0.changes': '',
  'car.revisions.1.miles': 20021,
  'car.revisions.1.code': 'REV02',
  'car.revisions.1.changes.0.type': 'asthetic',
  'car.revisions.1.changes.0.desc': 'Left tire cap',
  'car.revisions.1.changes.1.type': 'mechanic',
  'car.revisions.1.changes.1.desc': 'Engine pressure regulator',
  'visits.0.date': '2015-01-01',
  'visits.0.dealer': 'DEAL-001',
  'visits.1.date': '2015-03-01',
  'visits.1.dealer': 'DEAL-002',
};

const objKeys = Object.keys(data);

function assign(obj, keys, val) {
  const lastKey = keys.pop();
  const lastObj = keys.reduce((obj, key) => (obj[key] = obj[key] || {}), obj);
  lastObj[lastKey] = val;
}

const final = objKeys.reduce((acc, cv) => {
  if (!cv.includes('.')) {
    acc[cv] = data[cv];
  }

  const keys = cv.split('.');
  assign(acc, keys, data[cv]);

  return acc;
}, {});

console.log({ final });
quhf5bfb

quhf5bfb6#

type tsAppendableObj = { [key: string]: any }
const test = {
    r_0_0_1: {
        component: 'header_hosted_by',
        langs: 'header_hosted_by',
    },
    r_0_0_2: {
        component: 'header_lang',
        langs: '',
    },
    r_0_0_2_0: {
        component: 'header_lang_en',
        langs: 'header_lang_en',
    },
    r_0_0_2_1: {
        component: 'header_lang_fr',
        langs: 'header_lang_fr',
    },
    r_0: {
        component: 'title',
        langs: 'info_page_title',
    },
    r_0_0: {
        component: 'header',
        langs: 'api_version',
    },
    r_0_0_0: {
        component: 'header_date',
        langs: 'header_date',
    },
}

function unflatten2(data: tsAppendableObj, separator: string) {
    let result = <tsAppendableObj>{}
    let temp = <tsAppendableObj>{}
    let temp2 = <tsAppendableObj>{}
    let levels = <tsAppendableObj>{}
    let property
    let i

    for (property in data) {
        levels = property.split(separator)
        let gg = levels[0]
        temp = result
        for (i = 1; i < levels.length; i++) {
            gg = gg + separator + levels[i]
            if (!temp[gg]) {
                temp[gg] = {
                    main: {},
                    items: {},
                }
            }
            if (i === levels.length - 1) temp[gg].main = data[property]
            temp = temp[gg].items
        }
    }
    return result
}

console.log(unflatten2(test, '_'))

相关问题