/**
* 对象扁平化
* 说明:请实现 flatten(input) 函数,input 为一个 javascript 对象(Object 或者 Array),返回值为扁平化后的结果。
* var input = {
* a: 1,
* b: [ 1, 2, { c: true }, [ 3 ] ],
* d: { e: 2, f: 3 },
* g: null,
* }
* output如下
* {
* "a": 1,
* "b[0]": 1,
* "b[1]": 2,
* "b[2].c": true,
* "b[3][0]": 3,
* "d.e": 2,
* "d.f": 3,
* // "g": null, 值为null或者undefined,丢弃
* }
*/
<!DOCTYPE html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
let result = {};
const flatten = (params, key) => {
if (params instanceof Array) {
params.forEach((param, index) => {
if (param instanceof Object || param instanceof Array) {
flatten(param, `${key}[${index}]`);
} else {
result[`${key}[${index}]`] = flatten(param, `${key}[${index}]`);
}
});
} else if (params instanceof Object) {
for (var itemKey in params) {
const itemValue = params[itemKey];
if (itemValue instanceof Array) {
flatten(itemValue, itemKey);
} else if (itemValue instanceof Object) {
flatten(itemValue, itemKey);
} else if (itemValue === null || itemValue === undefined) {} else {
if (key) {
result[`${key}.${itemKey}`] = flatten(itemValue, itemKey);
} else {
result[itemKey] = flatten(itemValue, itemKey);
}
}
}
} else {
return params;
}
};
var input = {
a: 1,
b: [
1,
2, {
c: true
},
[3]
],
d: {
e: 2,
f: 3
},
g: null
};
flatten(input);
console.log(result);
</script>
</head>
<body>
<div>
<h1>Example Domain</h1>
<p>
<br>* 对象扁平化
<br>* 说明:请实现 flatten(input) 函数,input 为一个 javascript 对象(Object 或者 Array),返回值为扁平化后的结果。
<br>* 示例:
<br>* var input = {
<br>* a: 1,
<br>* b: [ 1, 2, { c: true }, [ 3 ] ],
<br>* d: { e: 2, f: 3 },
<br>* g: null,
<br>* }
<br>* var output = flatten(input);
<br>* output如下
<br>* {
<br>* "a": 1,
<br>* "b[0]": 1,
<br>* "b[1]": 2,
<br>* "b[2].c": true,
<br>* "b[3][0]": 3,
<br>* "d.e": 2,
<br>* "d.f": 3,
<br>* // "g": null, 值为null或者undefined,丢弃
<br>* }
<br>*/
<br>function flatten() {
<br> /* 代码实现 */
<br>}
</p>
</div>
</body>
</html>