gpt4 book ai didi

javascript - 创建具有所需树结构的对象

转载 作者:行者123 更新时间:2023-11-30 20:00:23 25 4
gpt4 key购买 nike

我一直在尝试创建一个树结构:

var result = {
email: {
schema: {
verified: 'email.verified',
email_address: 'email.email_address',
entity: {
schema: {
name: 'email.entity.name',
type: 'email.entity.type',
email: {
schema: {
verified: 'email.entity.email.verified',
email_address: 'email.entity.email.email_address'
}
}
}
}
}
}
};

从下面给出的数组数据:

var schema = {
'paths': [
'email.email_address',
'email.entity.email.email_address',
'email.entity.email.verified',
'email.entity.type',
'email.entity.name',
'email.verified',
'created_at',
'contact_numbers'
]
}

您看到我期望的输出具有嵌套在 n 级别中的 schema 属性,这是不可预测的。这取决于 paths 的值,例如 'email.entity.email.email_address'。您可以用点拆分它,看起来每个点都被输出中的 schema 属性替换。

我正在尝试使用递归,但我无法设置该流程。以下是我到目前为止尝试过的代码:

var schema = {
'paths': [
'email.email_address',
'email.entity.email.email_address',
'email.entity.email.verified',
'email.entity.type',
'email.entity.name',
'email.verified',
'created_at',
'contact_numbers'
]
}
var newSchema = {};

var key = 'email';
var existKeys = schema.paths.filter((path) => path.includes(key + '.'));
var requiredObject = {};
existKeys.forEach((existKey) => {
var splitKeys = existKey.split('.');
splitKeys.forEach((splitKey, index) => {
if (requiredObject[splitKey] && index + 1 === splitKeys.length) {
requiredObject[splitKey].schema = existKey;
} else {
requiredObject[splitKey] = {
'schema': {}
}
}
});
});
console.log(requiredObject);

最佳答案

您可以减少路径并为每个找到的键取一个 schema 属性。

var schema = { paths: ['email.email_address', 'email.entity.email.email_address', 'email.entity.email.verified', 'email.entity.type', 'email.entity.name', 'email.verified', 'created_at', 'contact_numbers'] },
result = schema.paths
.filter(s => s.startsWith('email')) // or not or so, if so, maybe
.reduce((r, p) => {
var keys = p.split('.'),
last = keys.pop();

keys.reduce((o, k) => (o[k] = o[k] || { schema: {} }).schema, r)[last] = p;
return r;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 创建具有所需树结构的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53443925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com