目标对象
var obj = {
a: {
info: {
name: 'Joe',
age: 18
}
},
b: {
hh: 'aadsf'
}
}
处理后变成这样
var obj = {
'a.info.name': 'Joe',
'a.info.age': 18,
'b.hh': 'aadsf'
}
如何实现呢,头大。。。
目标对象
var obj = {
a: {
info: {
name: 'Joe',
age: 18
}
},
b: {
hh: 'aadsf'
}
}
处理后变成这样
var obj = {
'a.info.name': 'Joe',
'a.info.age': 18,
'b.hh': 'aadsf'
}
如何实现呢,头大。。。
简单写了个嵌套
function flat (obj) {
let newObj = {}
function process (subObj, prefixArr) {
for (let k in subObj) {
let newArr = prefixArr.concat()
newArr.push(k)
if (Object.prototype.toString.call(subObj[k]) === '[object Object]') {
process(subObj[k], newArr)
} else {
newObj[newArr.join('.')] = subObj[k]
}
}
}
process(obj, [])
return newObj
}
let ret = flat(obj)
console.log(ret)
const isObject = (val) => typeof val === 'object'
function solution(obj, group = [], result = {}) {
Object.keys(obj).forEach(key => {
const val = obj[key]
const newGroup = group.slice()
newGroup.push(key)
if (isObject(val)) {
solution(obj[key], newGroup, result)
} else {
const groupKey = [...newGroup].join('.')
result[groupKey] = val
}
})
return result
}
const r = solution(obj)
console.log('r: ', r);
var flatten = function fn(obj, keys = []) {
return Object.keys(obj).reduce((current, next) => {
return Object.assign({}, current, Object.prototype.toString.call(obj[next]) === '[object Object]' ?
fn(obj[next], keys.concat([next])) : { [keys.concat([next]).join(".")]: obj[next] })
}, {})
}
var obj = {
a: {
info: {
name: 'Joe',
age: 18
}
},
b: {
hh: 'aadsf'
},
c: [4, 6]
};
var res = (function toArr(obj, kyes = []) {
return Object.entries(obj).reduce(
(acc, [key, val]) =>
Object.assign(
acc, val instanceof Object ?
toArr(val, kyes.concat(key)) :
{[kyes.concat(key).join('.')]: val}),
{})
})(obj);
console.log(res);
/*
{
a.info.age: 18,
a.info.name: "Joe",
b.hh: "aadsf",
c.0: 4,
c.1: 6
}
*/
10 回答11.6k 阅读
2 回答3.1k 阅读✓ 已解决
3 回答2.7k 阅读✓ 已解决
2 回答2.1k 阅读✓ 已解决
4 回答2.1k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
不要头大,递归就解决了