我在数组中嵌套了对象,我想使用 javascript 将它们转换为点符号字符串。
这是我用于转换过程的数据示例数据。
[
{
property: 'name',
children: [],
message: 'name should not be empty',
},
{
property: 'priceForm',
children: [
{
property: 'priceCurrency',
children: [],
message: 'priceCurrency should not be empty',
},
],
},
{
property: 'priceForm',
children: [
{
property: 'rolePrices',
children: [
{
property: '0',
children: [
{
property: 'markupType',
children: [],
message: 'markupType should not be empty',
},
],
},
],
},
],
},
]
预期结果是
{
'name': 'name should not be empty',
'priceForm.priceCurrency': 'priceCurrency should not be empty',
'priceForm.rolePrices.0.markupType': 'markupType should not be empty',
}
您可以先收集路径,然后再构建属性。
function getObject(array, path = '', target = {}) {
array.forEach(({ property, children = [], message }) => {
var temp = path + (path && '.') + property;
if (children.length) {
getObject(children, temp, target);
return;
}
target[temp] = message;
});
return target;
}
var array = [{ property: 'name', children: [], message: 'name should not be empty' }, { property: 'priceForm', children: [{ property: 'priceCurrency', children: [], message: 'priceCurrency should not be empty' }] }, { property: 'priceForm', children: [{ property: 'rolePrices', children: [{ property: '0', children: [{ property: 'markupType', children: [], message: 'markupType should not be empty' }] }] }] }],
object = getObject(array);
console.log(object);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句