gpt4 book ai didi

javascript - JS : convert array objects to dot string

转载 作者:行者123 更新时间:2023-12-01 00:45:18 25 4
gpt4 key购买 nike

我在数组中嵌套了对象,我想用 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);

关于javascript - JS : convert array objects to dot string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57433293/

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