-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
第 111 题:编程题,写个程序把 entry 转换成如下对象 #206
Comments
我先来function flatObj(obj, parentKey = "", result = {}) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
let keyName = `${parentKey}${key}`;
if (typeof obj[key] === 'object')
flatObj(obj[key], keyName+".", result)
else
result[keyName] = obj[key];
}
}
return result;
} |
function isObject (obj) {
return Object.prototype.toString.call(obj) === '[object Object]'
}
function flatObj (obj, prefix = '', res = {}) {
for (let i in obj) {
let key = prefix ? prefix + '.' + i : i
isObject(obj[i]) ? flatObj(obj[i], key, res) : (res[key] = obj[i])
}
return res
} |
var entry = {
a: {
b: {
c: {
dd: 'abcdd'
}
},
d: {
xx: 'adxx'
},
e: 'ae'
}
}
var keys = [];
function flatObj(from, to) {
for (var key in from) {
var res = from[key];
keys.push(key);
if (typeof res === "object") {
flatObj(res, to);
} else {
to[keys.join(".")] = res;
}
keys.pop();
}
}
var output = {};
flatObj(entry, output);
console.log(output); |
function en(obj) {
const keyArr = [];
const newObj = {};
const _c = function (o) {
for (k in o) {
keyArr.push(k);
if (typeof o[k] === 'object') {
_c(o[k]);
} else {
newObj[keyArr.join('.')] = o[k];
keyArr.pop();
}
}
keyArr.pop();
}
_c(obj);
return newObj;
} |
bfs function flatObj(entry) {
const queue = Object.entries(entry)
const res = {}
while (queue.length) {
const [key, obj] = queue.pop()
for (const [k, v] of Object.entries(obj)) {
if (typeof v !== 'object') {
res[`${key}.${k}`] = v
} else {
queue.push([`${key}.${k}`, v])
}
}
}
return res
} |
function func (origin, output = {}, keys = []) => {
if (typeof origin === 'object') {
for (const k in origin) {
generate(origin[k], output, [...keys, k])
}
} else {
output[keys.join('.')] = origin
}
}
const output = {}
func(entry, output)
console.log('output', output) |
|
function flat(obj, key = "", res = {}) {
Object.keys(obj).forEach(k => {
if (Object.prototype.toString.call(obj[k]) == "[object Object]") {
flat(obj[k], key + k + ".", res);
} else {
res[key + k] = obj[k];
}
});
return res;
}
console.log(flat(entry)); |
题目var entry = {
a: {
b: {
c: {
dd: 'abcdd'
}
},
d: {
xx: 'adxx'
},
e: 'ae'
}
};
// 要求转换成如下对象
var output = {
'a.b.c.dd': 'abcdd',
'a.d.xx': 'adxx',
'a.e': 'ae'
}; 实现方案思路 遍历对象,遇到还是对象的地方递归深入即可。 核心代码: /**
*
* @param {String | null} prevKey 前面的key
* @param {Object} obj 当前操作对象
* @returns {Array<Object>} 扁平化后的对象数组
*/
function getFlat(prevKey, obj) {
const arr = [];
Object.keys(obj).forEach(k => {
const currentKey = prevKey ? `${prevKey}.${k}` : k;
if (Object.prototype.toString.call(obj[k]) != '[object Object]') {
arr.push({
[currentKey]: obj[k]
});
} else {
arr.push(...getFlat(currentKey, obj[k]));
}
});
return arr;
} 以给定代码为例,即可转化为如下形式,然后进行合并即可。 [
{'a.b.c.dd': 'abcdd'},
{'a.d.xx': 'adxx'},
{'a.e': 'ae'},
] 如果不考虑纯函数的问题,可以初始就定义一个空对象,然后在递归函数中直接将每次的结果写入,这样就少了后续的合并操作,详见后续实现中的 完整代码var entry = {
a: {
b: {
c: {
dd: 'abcdd'
}
},
d: {
xx: 'adxx'
},
e: 'ae'
}
};
/**
* 对象扁平化
* @param {Object} obj 操作对象
* @returns {Object} 扁平化后的对象
*/
function flatObject(obj) {
const flat = {};
return Object.assign(flat, ...getFlat(null, obj));
/**
*
* @param {String | null} prevKey 前面的key
* @param {Object} obj 当前操作对象
* @returns {Array<Object>} 扁平化后的对象数组
*/
function getFlat(prevKey, obj) {
const arr = [];
Object.keys(obj).forEach(k => {
const currentKey = prevKey ? `${prevKey}.${k}` : k;
if (Object.prototype.toString.call(obj[k]) != '[object Object]') {
arr.push({
[currentKey]: obj[k]
});
} else {
arr.push(...getFlat(currentKey, obj[k]));
}
});
return arr;
}
}
console.log(JSON.stringify(flatObject(entry), 0, 4));
// {
// "a.b.c.dd": "abcdd",
// "a.d.xx": "adxx",
// "a.e": "ae"
// }
/**
* 对象扁平化
* @param {Object} obj 操作对象
* @returns {Object} 扁平化后的对象
*/
function flatObject2(obj) {
const flat = {};
getFlat(null, obj);
return flat;
/**
* 递归将对象扁平化
* @param {String | null} prevKey 前面的key
* @param {Object} obj 当前操作对象
*/
function getFlat(prevKey, obj) {
Object.keys(obj).forEach(k => {
const currentKey = prevKey ? `${prevKey}.${k}` : k;
if (Object.prototype.toString.call(obj[k]) != '[object Object]') {
flat[currentKey] = obj[k];
} else {
getFlat(currentKey, obj[k]);
}
});
}
}
console.log(JSON.stringify(flatObject2(entry), 0, 4));
// {
// "a.b.c.dd": "abcdd",
// "a.d.xx": "adxx",
// "a.e": "ae"
// } |
function flatObj(entry){
function rec (entry, parentKey , result){
Object.keys(entry).forEach((key) => {
if(typeof entry[key] === 'object') {
rec(entry[key], parentKey + key, result)
} else {
const keyname = parentKey.replace(/(?=\B)/g, '.')+ '.' +key
result[keyname] = entry[key]
}
})
}
rec(entry, parentKey = '', result = {})
return result
} |
function flatObj(obj) { |
|
function flatJson(obj = {}, parentKey = '', res = {}) {
for (let k in obj) {
if (typeof obj[k] !== 'object' && obj[k] !== null) {
res[`${parentKey}${k}`] = obj[k];
} else {
flatJson(obj[k], `${parentKey}${k}.`, res);
}
}
return res;
} 大相径庭 |
var entry = {
a: {
b: {
c: {
dd: 'abcdd'
}
},
d: {
xx: 'adxx'
},
e: 'ae'
}
}
/**
* [getFlat]
* @param {[Object]} entry [传入对象]
* @param {String} hea [属性名前缀]
* @param {Object} res [返回对象]
*/
function getFlat (entry, hea = '', res = {}) {
for (let k in entry) {
if (entry.hasOwnProperty(k)) {
if (Object.prototype.toString.call(entry[k]) === '[object Object]' ) {
getFlat(entry[k], hea + k + '.', res)
} else {
res[hea + k] = entry[k]
}
}
}
return res
}
console.log(getFlat(entry))
// 1.先遍历,判断是否包含属性
// 2.属性值是对象继续递归
// 3.属性值不是对象返回 |
const flattenObject = (obj, prefix = '') =>
Object.keys(obj).reduce((acc, k) => {
const pre = prefix.length ? prefix + '.' : '';
if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k));
else acc[pre + k] = obj[k];
return acc;
}, {}) |
|
function fun111(entry) { |
`var entry = {
|
var entry = {
a: {
b: {
c: {
dd: 'abcdd'
}
},
d: {
xx: 'adxx'
},
e: 'ae'
}
}
const deepFlat = (obj) => {
let res = {}
function deep(obj, prekey = '') {
for (let key of Object.keys(obj)) {
if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
deep(obj[key], prekey ? `${prekey}.${key}` : key)
} else {
res[`${prekey}.${key}`] = obj[key]
}
}
}
deep(obj)
return res
}
console.log(deepFlat(entry)) |
function fun1(obj, str = '', result = {}) {
Object.keys(obj).forEach((key) => {
if (typeof obj[key] == 'object') {
fun1(obj[key], str + key + '.', result)
} else {
str += key
result[str] = obj[key]
}
})
return result
} console.log(fun1(entry)) |
上一版typescript实现function transformObject(input: any, keyStr: string='', result: any={}): any{
const keys: Array<string> = Object.keys(input);
keys.map(key => {
if (typeof input[key] === 'object') {
transformObject(input[key], keyStr+`${key}.`, result)
} else {
keyStr += `${key}`;
result[keyStr] = input[key];
}
})
return result
} |
const isObject = (value) => (typeof value === 'object') && (value !== null)
function reduceObject(obj, parentName, resultObj) { // 对 {} 的每个值进行判断
const keyNames = Object.keys(obj); // ['b', 'd']
keyNames.forEach(keyName => {
let currentValue = obj[keyName] // 当前值
let currentKeyName = parentName ? `${parentName}.${keyName}` : keyName // 当前键名
// 键值为对象则继续递归, 为其它值则将新的键值对添加到result中
if(isObject(currentValue)) {
reduceObject(currentValue, currentKeyName, resultObj)
} else {
resultObj[currentKeyName] = currentValue
}
})
}
function flatKeyName(obj) {
let outputObj = {}
reduceObject(entry, null, outputObj)
return outputObj
}
console.log(flatKeyName(entry)) |
function isPlainObject(obj){
return Object.prototype.toString.call(obj) === '[object Object]'
}
const output = {}
function parserObj(obj,parentKey=''){
if(isPlainObject(obj)){
Object.keys(obj).forEach(key=>{
parserObj(obj[key],`${parentKey}${key}.`)
})
}else{
output[parentKey] = obj
}
}
var entry = {
a: {
b: {
c: {
dd: 'abcdd'
}
},
d: {
xx: 'adxx'
},
e: 'ae'
}
}
parserObj(entry)
console.log(output) |
function flatObj(preKey, obj, result = {}) {
if (JSON.stringify(obj) === '{}') {
return {};
}
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const curKey = preKey ? `${preKey}.${key}` : key;
if (typeof obj[key] !== 'object') {
result[curKey] = obj[key];
} else {
flatObj(curKey, obj[key], result);
}
}
}
return result;
} |
function flatObj(entry, prev = "", result = {}) {
Object.keys(entry).map((key) =>
typeof entry[key] === "object"
? flatObj(entry[key], prev ? key : `${prev}.${key}`, result)
: (result[prev ? key : `${prev}.${key}`] = entry[key])
);
return result;
} |
|
var entry = {
a: {
b: {
c: {
dd: 'abcdd',
},
},
d: {
xx: 'adxx',
},
e: 'ae',
},
}
function flatPlainObj(entry) {
if (Object.prototype.toString.call(entry) !== '[object Object]') {
throw new Error('entry must be a plain object')
}
var output = {}
var pathArr = []
function recur(entry) {
if (Object.prototype.toString.call(entry) === '[object Object]') {
Object.keys(entry).forEach(key => {
pathArr.push(key)
recur(entry[key])
pathArr.pop()
})
} else {
output[pathArr.join('.')] = entry
}
}
recur(entry)
return output
}
console.log(flatPlainObj(entry)) |
function flattern(o, path = '', res = {}) {
Object.keys(o).forEach((key) => {
if (Object.prototype.toString.call(o[key]) === '[object Object]' || Array.isArray(o[key])) {
flattern(o[key], `${path}.${key}`, res)
} else {
res[`${path}.${key}`.slice(1)] = o[key]
}
});
return res
} |
深度遍历
|
function f1() {
var cc =f1()(entry); |
整体思路:递归深入获取属性字符串,闭包保存拼接的字符串,每次递归结束则去除遍历的属性值
|
|
对象的扁平化,没有说数组和空对象怎么处理,那就按默认处理了
|
|
|
遍历树
|
function flatObj(obj,key='',result={}){
if(typeof obj !== 'object' || obj===null){
result[key] = obj
return
}
Object.keys(obj).forEach(k=>{
flatObj(obj[k], `${key}${key?'.':''}${k}`,result)
})
return result
} |
|
const isObj = (a) => typeof a === 'object' && a !== null;
const simpleObj = (obj) => {
const stack = [obj];
let current;
const out = {};
const _p = Symbol('_p');
const _pNode = Symbol('_pNode');
while(stack.length) {
current = stack.pop();
if (isObj(current)) {
Object.keys(current).reverse().forEach(key => {
stack.push(current[key]);
if (!isObj(current[key])) {
let temp = key;
let currentTemp = current;
while(currentTemp && currentTemp[_p]) {
temp = `${currentTemp[_p]}.${temp}`;
currentTemp = currentTemp[_pNode];
}
out[temp] = current[key];
} else {
current[key][_pNode] = current;
current[key][_p] = key;
}
});
}
}
return out;
}
var entry = {
a: {
b: {
c: {
dd: 'abcdd'
}
},
d: {
xx: 'adxx'
},
e: 'ae'
}
}
console.log(simpleObj(entry)); |
function transformObj(obj) {
const newObj = {}
const objArray = []
const topKey = Reflect.ownKeys(obj).shift()
const firstKey = obj[topKey]
Reflect.ownKeys(firstKey).forEach((key) => objArray.push(JSON.stringify({ [key]: firstKey[key] })))
const resultArray = objArray.map((item) => item.replace(/{|"|}|/g, ''))
resultArray.forEach((item) => {
const key = item.split(':')
const value = key.pop()
newObj[topKey + '.' + key.toString().replace(/,/g, '.')] = value
})
return newObj
}
transformObj(entry) 思路是解析为字符串再转换 |
var entry = {
a: {
b: {
c: {
dd: 'abcdd'
}
},
d: {
xx: 'adxx'
},
e: 'ae'
}
}
function change(entry, fkey = '', res = {}){
if(typeof entry != 'object'){
res[fkey] = entry
return
}
for(let key in entry){
if(fkey !== ''){
change(entry[key], `${fkey}.${key}`, res)
}else{
change(entry[key], `${key}`, res)
}
}
return res
}
console.log(change(entry)) |
bfs的话应该queue.shift(),另外没考虑{a:1}这种情况,按你代码输出是{},简单修改下: function flatObj(entry) {
const queue = Object.entries(entry)
const res = {}
while (queue.length) {
const [key, obj] = queue.shift()
if (typeof obj === 'object') {
for (const [k, v] of Object.entries(obj)) {
queue.push([`${key}.${k}`, v])
}
} else {
res[key] = obj
}
}
return res
} |
function flatObj(obj) {
let res = {}
function dfs(str, obj) {
if (typeof obj !== 'object') {
res[str] = obj
return
}
for (let i in obj) {
let s = str === '' ? i : `${str}.${i}`
dfs(s, obj[i])
}
}
dfs('', obj)
return res
} |
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]'
}
function parseToObj(obj, paths = []) {
if (!isObject(obj)) {
return paths.length > 0
? { [paths.join('.')]: obj }
: obj
}
return Object.keys(obj).reduce((res, key) => {
Object.assign(res, parseToObj(obj[key], paths.concat(key)))
return res
}, {})
}
const testObj = {
a: {
b: {
c: {
dd: 'abcdd'
}
},
d: {
xx: 'adxx'
},
e: 'ae'
}
}
console.log(parseToObj(testObj)) |
|
function convert(entry) {
let obj = {};
helper(entry, "", obj);
return obj
}
function helper(entry, pKey, obj) {
for (const key in entry) {
if (typeof entry[key] == "string") {
let keyname = `${pKey}${key}`;
obj[keyname] = entry[key];
} else {
helper(entry[key], `${pKey}${key}.`, obj);
}
}
} |
const trans = (entry) => {
let outPut = {}
const run = (entry, name = '') => {
const keys = Object.keys(entry)
for(let key of keys) {
let v = entry[key]
let t = name ? `${name}.${key}` : key
if(typeof v !== 'object') {
outPut[t] = v
}else {
run(v, t)
}
}
}
run(entry)
return outPut
}
trans(entry) |
function format(entry) {
const result = {}
recur(entry)
return result
function recur(obj, path = []) {
Object.keys(obj).forEach((key) => {
const value = obj[key]
if (typeof value === 'object') {
recur(value, [...path, key])
} else {
const id = path.length ? `${path.join(".")}.${key}` : key
result[id] = value;
}
})
}
}
var entry = {
a: {
b: {
c: {
dd: "abcdd",
},
},
d: {
xx: "adxx",
},
e: "ae",
},
};
console.log("debug-", format(entry)); |
|
// 递归解法
var entry = {
a: {
b: {
c: {
dd: 'abcdd'
}
},
d: {
xx: 'adxx'
},
e: 'ae'
}
}
// 要求转换成如下对象
var output = {
'a.b.c.dd': 'abcdd',
'a.d.xx': 'adxx',
'a.e': 'ae'
}
function transform(entry) {
let output = {};
function _inner(target, path) {
if (target === null || typeof target !== 'object') {
return output[path] = target;
}
Reflect.ownKeys(target).forEach(key => {
_inner(target[key], path ? `${path}.${key}` : `${key}`);
});
}
_inner(entry, '');
return output;
}
console.log(transform(entry)); |
function flatObj(obj) {
var res = {}
function dfs(obj, preKey = '') {
Reflect.ownKeys(obj).forEach(key => {
var keyName = `${preKey}${key}`
if(typeof obj[key] === 'object') {
dfs(obj[key], keyName + '.')
} else {
res[keyName] = obj[key]
}
})
}
dfs(obj)
return res
}
flatObj(entry) |
/**
* 1. 对象扁平化
*/
function flat(obj, pre = '', result = {}) {
Object.keys(obj).forEach((v) => {
const key = `${preKey}${v}`
if (typeof obj[v] === 'object') {
flat(obj[v], `${key}.`, result)
} else {
result[key] = obj[v]
}
})
return result
}
const flatResult = flat(entry, '', {})
console.log(flatResult)
/**
* 2. 扁平化对象重组
*/
function restore(obj) {
let result = {}
Object.keys(obj).forEach((v) => {
const list = v.split('.')
const value = obj[v]
list.reduce((res, item, index) => {
if (index === list.length - 1) {
res[item] = value
} else {
res[item] = res[item] ? res[item] : {}
}
return res[item]
}, result)
})
return result
}
console.log(JSON.stringify(restore(flatResult), null, 4)) |
const find666 = (entry) => {
} |
利用构造函数
|
回溯解决
|
function flatten(obj) {
var res = {};
function flat(obj, key) {
if (obj === null || Object(obj) !== obj) {
res[key] = obj;
} else if (Array.isArray(obj)) {
var len = obj.length;
if (len < 1) {
res[key] = [];
return;
}
for (var i = 0; i < len; i++) {
flat(obj[i], key ? `${key}[${i}]` : key + '');
}
} else {
for (var k in obj) {
flat(obj[k], key ? `${key}.${k}` : k);
}
}
}
flat(obj, '');
return res;
}
var obj = {
a: {
b: 1,
c: 2,
d: {
e: 5
}
},
b: [1, 3, {
a: 2,
b: 3
}],
c: 3
}
flatten(obj) |
var entry = {
a: {
b: {
c: {
dd: 'abcdd'
}
},
d: {
xx: 'adxx'
},
e: 'ae'
}
}
function flatObj(obj, preKey = '') {
let res = {};
for (let key in obj) {
let value = obj[key];
let newKey = preKey ? `${preKey}.${key}` : key;
if (typeof obj[key] === 'object') {
flatObj(obj[key], newKey)
} else {
res[newKey] = value;
}
}
}
console.log(flatObj(entry)) |
|
function format(obj) {
const result = {};
const acc = [];
dfs(obj);
return result;
function dfs(r) {
for (let key in r) {
if (typeof r[key] !== "object") {
result[[...acc].join(".") + "." + key] = r[key];
} else {
acc.push(key);
dfs(r[key]);
acc.pop();
}
}
}
}
// output = {
// 'a.b.c.dd': 'abcdd',
// 'a.d.xx': 'adxx',
// 'a.e': 'ae'
// }
console.debug(
format({
a: {
b: {
c: {
dd: "abcdd",
},
},
d: {
xx: "adxx",
},
e: "ae",
},
})
); |
The text was updated successfully, but these errors were encountered: