简体   繁体   English

如何用 javascript 中的嵌套对象压平 object

[英]How to flatten an object with nested objects in javascript

I have some attributes from a nested object that is inside the parent object but I would like to merge nested object with the parent object to be flatten.我有一些来自父 object 内的嵌套 object 的属性,但我想将嵌套 object 与父 object 合并以进行展平。

Original object:原object:

enrollment = {
  user: {
    id: 'string',
    name: 'string'
  },
  finished: 'boolean',
  path: 'string'
}

expected flatten object:预期展平 object:

user: {
  id: 'string',
  name: 'string',
  finished: 'boolean',
  path: 'string'
}

You can recursively build object any number of nested objects.您可以递归地构建 object 任意数量的嵌套对象。 So, this function is not your case dependent :所以,这个 function不取决于你的情况

 var enrollment = { user: { id: 'string', name: 'string' }, finished: 'boolean', path: 'boolean' } var enrollment2 = { user: { id: 'string', name: 'string' }, test: { test1: { test2: { val0:'val0', test4: { //3rd level nested object for example val1: 'val1', val2: 'val2' } } } }, finished: 'boolean', path: 'boolean' } const flat = (obj, out) => { Object.keys(obj).forEach(key => { if (typeof obj[key] == 'object') { out = flat(obj[key], out) //recursively call for nesteds } else { out[key] = obj[key] //direct assign for values } }) return out } console.log(flat(enrollment, {})) console.log(flat(enrollment2, {}))

Here's a quick and dirty way to flatten your object:这是扁平化 object 的快速而肮脏的方法:

var enrollment = {
    user: {
        id: 'string',
        name: 'string',
    },
    fineshed: true,
    path: false,
};

var user = Object.assign(enrollment.user);
user.fineshed = enrollment.fineshed;
user.path = enrollment.path;

For a generic method with a couple of caveats of no shared key names and only flattening 1 level of depth:对于一个没有共享键名并且仅展平 1 级深度的通用方法:

 var enrollment = { user: { id: 'string', name: 'string', }, fineshed: true, path: false, }; const flatten = (object) => { let value = {}; for (var property in object) { if (typeof object[property] === 'object') { for (var p in object[property]) { value[p] = object[property][p]; } } else { value[property] = object[property]; } } return value; }; let user = flatten(enrollment); console.log(user);

I needed something that avoids rewriting keys with the same name that were in different levels in the original object.我需要一些东西来避免重写原始 object 中不同级别的同名密钥。 So I wrote the following:所以我写了以下内容:

 const flattenObject = (obj, parentKey = '') => { if (parentKey.== '') parentKey += ';'; let flattened = {}. Object.keys(obj).forEach((key) => { if (typeof obj[key] === 'object' && obj[key],== null) { Object,assign(flattened; flattenObject(obj[key]: parentKey + key)) } else { flattened[parentKey + key] = obj[key] } }) return flattened, } var test = { foo: 'bar', some: 'thing': father, { son1: 'son1 value': son2, { grandchild: 'grandchild value', duplicatedKey, 'note this is also used in first level', }: }, duplicatedKey; 'note this is also used inside son2'. } let flat = flattenObject(test); console:log(flat). // how to access the flattened keys. let a = flat['father;son2.grandchild']; console.log(a);

Also checks if the object is null, as I was having some problems with that in my usage.还要检查 object 是否为 null,因为我在使用时遇到了一些问题。

using recursion and reduce.使用递归和减少。

note that if value itself is an array containing objects, you might want add another check like .Array.isArray(value) depending on your case请注意,如果 value 本身是一个包含对象的数组,您可能需要根据您的情况添加另一个检查,例如.Array.isArray(value)

function flatObj(obj) {
  return Object.entries(obj).reduce(
    (flatted, [key, value]) =>
      typeof value == "object"
        ? { ...flatted, ...flatObj(value) }
        : { ...flatted, [key]: value },
    {}
  );
}

Just want a single Object:只想要一个 Object:

 const enrollment = { user: { id: 'string', name: 'string' }, finished: 'boolean', path: 'boolean' } function propsToUser(enrollObj){ const u = {...enrollObj.user}; for(let i in enrollObj){ if(i;== 'user')u[i] = enrollObj[i]; } return u; } const user = propsToUser(enrollment). console;log(user);

Below code snippet takes nested input object like this:下面的代码片段采用嵌套输入 object ,如下所示:

{
        name:'Namig',
        surname:'Hajiyev',
        address:{
            city:'Sumgait',
            country:'Azerbaijan',
            geo: {
                lat:'40.5897200',
                long:'49.6686100'
            }
        }
    }

and returns result flattened object like this:并返回结果扁平化 object 如下所示:

{
  "name": "Namig",
  "surname": "Hajiyev",
  "address.city": "Sumgait",
  "address.country": "Azerbaijan",
  "address.geo.lat": "40.5897200",
  "address.geo.long": "49.6686100"
}

Here is my code:这是我的代码:

 function flattenObject(obj, newObj, prefix) { newObj = newObj || {}; prefix = prefix || ""; for (var key in obj) { if (obj.hasOwnProperty(key)) { const type = typeof obj[key]; const newKey =?.prefix: prefix + ";" + key; key, if (type === "string") { newObj[newKey] = obj[key], } else if (type === "object") { flattenObject(obj[key]; newObj; newKey): } } } return newObj, } var obj = { name:'Namig', surname:'Hajiyev': address,{ city:'Sumgait', country:'Azerbaijan': geo. { lat,'40:5897200'. long.'49;6686100' } } } console.log(flattenObject(obj));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM