【发布时间】:2021-11-23 23:12:47
【问题描述】:
我有多个 json5 文件需要加入一个对象。
其他文件将加入的主要对象示例:
/equations/mass-energy-equivalence.json5
{
name: 'Mass-energy equivalence',
expression: 'E=mc^{2}',
expressionIntern: '\\mag{E}=\\mag{m}\\const{c}^{2}',
description: '...',
categories: ['physics'],
units: [
'joule'
],
constants: [
'speed-of-light'
],
magnitudes: [
'energy', 'mass'
],
values: [
{ value: 1000, units: ['joule'] }
]
}
/magnitudes/energy.json5
{ name: 'Energy', symbol: 'E', slug: 'energy', units: ['joule'], description: '', ... }
所以幅度有单位,我必须加入units/joule 和magnitudes/energy,最后加入第一个对象。
/units/joule.json5
{ name: 'Joule', symbol: 'J', slug: 'joule', description: '', ... }
等等。
我需要加入:类别、单位、常数和幅度。就像 MySQL 加入一样。幅度也有单位,所以它们也必须加入。 所以我正在尝试做一个函数来获取这样的嵌套属性数组:
这是函数的输入:
const nestedProperties = [
'categories.slug',
'constants.slug.units.slug',
'magnitudes.slug',
'units.slug',
'variables.slug.units.slug',
'values.units.slug'
];
需要为所有nestedProperties 执行此操作。 最终的对象将是输出:
https://i.stack.imgur.com/yat2V.jpg
我有一个函数可以获取数据await getData(),所以我需要这个递归函数来设置data.categories = await getData('categories', slug: 'physics')
我的想法是这样的……但还没有完成。
getAllData(object, nestedProperties) {
nestedProperties.forEach(async (item) => {
const parts = item.split('.');
const size = parts.length;
// We need at least two parts to get the data.
if(size === 0) console.error('Invalid Path');
// Size is even so is a multiple of 2
// ex. categories.slug
if(size % 2 === 0) {
for(let i = 0; i < size - 2; i += 2) {
// path.property -> categories.slug
if(i == 0) {
let path = parts[i];
let property = parts[i + 1];
// If the path is in the data and is an array with items
// ex. data[categories]
if(Array.isArray(data[path]) && data[path].length > 0) {
// Iterate
for(let i = 0; i < data[path].length; i++) {
// path => 'categories',
// data[path] => 'physics'
data[path] = getData(path, data[path]);
// Recursive data[path] = getAllData(path, data[path])
}
} else {
data[path] = getAllData(path, data[path])
}
}
}
} else {
// Is odd so we need to do it a bit different
// ex. 'values.units.slug'
}
}
}
尝试了很多但没有成功获得 2 或 3 嵌套属性:[ 非常感谢。
【问题讨论】:
-
澄清
nestedProperties是如何产生的 -
示例:'categories.slug' 类别是文件所在的路径,而 slug 是我获取文件的属性。所以这表示:
categories/physics.json5from:javascript { name: 'Mass-energy equivalence', ... categories: ['physics'],它可以是字符串或数组。就像mysql的外键一样 -
我认为您在这里遗漏了一些信息。
"variables"在哪里使用?什么是"symbol"、"description"和"type",它们来自哪里?您的第一个 JSON 样本是输入,最后一个是输出吗?"constants.slug.units.slug"如何在示例输出中表示? -
另外,
getData('categories', slug: 'physics')不是合法的语法。你的意思是像getData('categories', {slug: 'physics'})(注意花括号。)或者它应该是不同的东西? -
我明白了。有
categories/physics.json5(categories.slug)、constants/speed-of-light.json5(constants.slug)、units/a.json5, b.json5, etc..、(units.slug) 的文件。因此,nestedProperties 数组表示我如何以及从何处获取第一个(输入)要加入的其他文件。第一个是将从其他 json 文件获取所有数据的对象,是的,最后一个是 otuput,如何第一个 json 将与所有其他 json 文件一起查看。
标签: javascript json function recursion