展平物体的一种优雅方法

时间:2019-07-05 13:47:35

标签: javascript arrays object reduce higher-order-functions

我正面临着一个琐碎的问题,就是要在内部嵌套一个嵌套的简单对象。

尝试过SO解决方案,但会引发错误:

const newWeather = Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}({id: 1}))

// also tried these ones:

    console.log(Object.keys(weatherDetails).reduce((a, b, c) => {
        return Object.assign(a, {
            a: b
        })
    }, {})); 

// another one

let newWeather = Object.assign({}, (function() {
        var obj = {}
        for (var i = 0; i < Object.keys(weatherDetails).length; i++) {
            console.log(i, Object.keys(weatherDetails))
            obj[Object.keys(weatherDetails)] = weatherDetails[Object.keys(weatherDetails)]
        }
        return obj
    })())

这是我需要弄平的物体,所以我们需要把它转过来:

{ 
    temperature: null, 
    humidity: null, 
    pressure: null, 
    windspeed: null, 
    pollution: {
        PM1: 1,
        PM10: 2,
        PM25: 3
    }
}

对此:

{ 
    temperature: null, 
    humidity: null, 
    pressure: null, 
    windspeed: null, 
    PM1: 1,
    PM10: 2,
    PM25: 3
}

7 个答案:

答案 0 :(得分:1)

假设您想要一个通用的解决方案,而不是使用静态密钥自定义到pollution示例的解决方案,那么这是一种快速的解决方法:

您只需遍历对象的属性键。如果属性是对象(我们称其为子对象),则将子对象的属性复制到主对象。

const obj = {
    temperature: null,
    humidity: null,
    pressure: null,
    windspeed: null,
    pollution: {
        PM1: 1,
        PM10: 2,
        PM25: 3
    }
};

function flatten(object) {
    for (const key in object) {
        if (!object.hasOwnProperty(key)) {
            continue;
        }

        if (typeof object[key] === 'object' && !Array.isArray(object[key]) && object[key] != null) {
            const childObject = object[key];
            delete object[key];
            object = {...object, ...childObject};
        }
    }
    return object;
}

console.log(flatten(obj));

答案 1 :(得分:1)

使用Object.entries()方法会更容易

您遍历对象的键和值,删除所有具有对象作为值的条目,并将该值后的条目分配给该对象。

let a = { 
    temperature: null, 
    humidity: null, 
    pressure: null, 
    windspeed: null, 
    pollution: {
        PM1: 1,
        PM10: 2,
        PM25: 3
    }
}

Object.entries(a).map(([key, value]) => {
    if(value && typeof value === 'object') {
         delete a[key];  // Delete entry
         Object.assign(a, value); // Add values from entry to object
    }
});

console.log(a)

一个班轮:

Object.entries(a).map(([key, value]) => value && typeof value === 'object' && delete a[key] && Object.assign(a, value));

这也是一种不变的功能方法:

Object.fromEntries(Object.entries(a).map(([key, value]) => 
    value && typeof value === 'object' ? 
         Object.entries(value) : [[key, value]]
).flat());

我个人更喜欢这最后一种方法,因为它不会突变原始对象或任何对象。

答案 2 :(得分:1)

只是共享一种不同的方法(也许足够优雅),这是一种依靠函数生成器递归展平对象的解决方案。

由于它依赖于函数生成器,因此最终可以动态地构建对象并跳过不需要的键,因为结果是可迭代的。

以下示例也有意使处理数组和null值稍微复杂一些,尽管原始问题中并不需要。

const original = { 
    temperature: null, 
    humidity: null, 
    pressure: null, 
    windspeed: null, 
    arrayKey: [1,2,3,'star!'],
    fnKey: function(i) {
      return i * 3;
    },
    pollution: {
        PM1: 1,
        PM10: 2,
        PM25: 3
    }
};
// Flattens an object.
function* flattenObject(obj, flattenArray = false) {
  // Loop each key -> value pair entry in the provided object.
  for (const [key, value] of Object.entries(obj)) {
    // If the target value is an object and it's not null (because typeof null is 'object'), procede.
    if (typeof(value) === 'object' && value !== null) {
      // if the targeted value is an array and arrays should be flattened, flatten the array.
      if (Array.isArray(value) && flattenArray) yield* flattenObject(value);
      // Otherwise, if the value is not an array, flatten it (it must be an object-like or object type).
      else if (!Array.isArray(value)) yield* flattenObject(value);
      // otherwise, just yield the key->value pair.
      else yield [key, value];
    }
    // otherwise, the value must be something which is not an object, hence, just yield it.
    else yield [key, value];
  }
}

// usage: assign to a new object all the flattened properties, using the spread operator (...) to assign the values progressively.
const res = Object.fromEntries(flattenObject(original));
console.log(res);
// sample usage by flattening arrays as well.
const res_flattened_arrays = Object.fromEntries(flattenObject(original, true));
console.log(res_flattened_arrays);
// custom object building by skipping a desired key
const resWithoutTemperature = {};
for (const [key, value] of flattenObject(original)) {
  if (key !== 'temperature') resWithoutTemperature[key] = value;
}
console.log(resWithoutTemperature);

答案 3 :(得分:0)

只需合并和删除作为Object实例的每个子属性。

let obj =
{ 
    temperature: null, 
    humidity: null, 
    pressure: null, 
    windspeed: null, 
    pollution: {
        PM1: 1,
        PM10: 2,
        PM25: 3,
		pollution: 4
    }
};

function flatten(obj)
{
	obj = Object.assign({}, obj);
	
	for (let i in obj)
		if (obj[i] instanceof Object)
		{
			obj = Object.assign(obj, obj[i]);

			// Prevent deletion of property i/"pollution", if it was not replaced by one of the child object's properties
			if (obj[i] === obj[i][i])
				delete obj[i];
		}
	
	return obj;
}

let obj_flattened = flatten(obj);
console.log(obj_flattened);

答案 4 :(得分:0)

我通常将Lodash用于此类转换。 有了它,这样做非常简单。

查看以下代码示例:

Data Source=10.10.10.150\SQLEXPRESS;Initial Catalog=db;User ID=sa;Password=pass;Connect Timeout=0

答案 5 :(得分:0)

尝试执行此操作(它将展平任何对象中包含的所有对象),以遍历对象属性并确定某个属性是否为另一个要展平的对象并添加到“根”对象:

var o = { 
    temperature: null, 
    humidity: null, 
    pressure: null, 
    windspeed: null, 
    pollution: {
        PM1: 1,
        PM10: 2,
        PM25: 3,
        newobject:{
            a:1,
            b:2,
            c: {
                x:3,
                y:4,
                z:5                 
            }
        }
    }
}

    function flatten(obj){
        let retObj = {};
        let objConst = {}.constructor;
        for (el in obj){
            if(obj[el] !== null && obj[el].constructor === objConst){
                retObj = Object.assign({}, retObj, flatten(obj[el]));
            } else {
                retObj[el] = obj[el];
            }
        }
        return retObj;
    }

    console.log(flatten(o));

答案 6 :(得分:-2)

如果您需要平整对象而不需要其他操作,并且对象层可能为n +,并且属性的类型各不相同,那么我建议使用简单的方法:

JSON.stringify(object);