我不确定为什么这样做。它似乎可以达到我的期望,但是我不确定它是如何工作的。有人可以解释如何在console.log中找到密钥并返回重新映射吗?
const data = {
title: "hello world",
user: {
title: 'ruegen',
app: {
title: 'my app'
}
}
}
const map = {
'user.title': 'Ruegen',
'title': 'Title',
'user.app.title': 'App'
}
Object.keys(map).forEach(function(key) {
const row = ref(data, key)
const header = map[key]
console.log(header, row)
})
function ref(row, key) {
var headers = key.split(".")
var row = JSON.parse(JSON.stringify(row))
headers.forEach(function(header) {
// console.log('>>', header)
try {
row = row[header]
} catch (err) {
return
}
})
return row;
}
主要工作在ref
功能上完成。您可以删除var row = JSON.parse(JSON.stringify(row))
,它将仍然有效。在该函数中,您将键字符串拆分为数组headers
(由key.split(".")
),然后在(标题元素的)forEach循环中,通过“ row = row [header]”进入对象行-因此,在每次迭代时,都用键“标头”。一切都在try-catch块中完成,因此如果您输入的密钥无效,则不返回任何内容。
在Object.keys(map).forEach
您运行ref
具有相同数据结构,但是从地图对象不同的密钥。
在ref
可以简化为
function ref(row, key) {
key.split(".").forEach(k => row ? row=row[k] : undefined)
return row;
}
在这里,我们使用三元运算符通过简单的null检查(这会提高无效密钥的代码速度)来替换try-catch块。和箭头功能。
const data = {
title: "hello world",
user: {
title: 'ruegen',
app: {
title: 'my app'
}
}
}
const map = {
'user.title': 'Ruegen',
'title': 'Title',
'user.app.title': 'App'
}
Object.keys(map).forEach(function(key) {
const row = ref(data, key)
const header = map[key]
console.log(header, row)
})
function ref(row, key) {
key.split(".").forEach(k => row ? row=row[k] : undefined)
return row;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句