gpt4 book ai didi

Javascript |通过点符号映射到对象

转载 作者:行者123 更新时间:2023-11-28 11:43:15 24 4
gpt4 key购买 nike

我目前有一个类似于以下的字符串 author.id .

本质上我想要做的就是将此字符串转换为对象。第一个成为关系,最后一个成为属性。然而,该列表实际上可能会变得更长,例如:

author.sites.id然后它将成为以下对象:

{
author: {
relationships: {
sites: {
attributes: {
id: 1
}
}
}
}
}

对象上始终有一个顶级属性 relationships因为这就是这样做的目的,将其映射到 JSON API 规范 POST 请求。

所以 author.id 的例子将生成具有以下属性的对象:

{
relationships: {
author: {
attributes: {
id:
}
}
}
}

因此基本上所有属性都被 . 分割应嵌套在 relationships 的父属性内最后一个应该始终是 attributes .

我知道你可能会为此使用reduce,并且我根据Stack Overflow上的其他问题创建了以下函数,但它不能正确执行嵌套,任何没有 attributes作为输出的最终对象的属性。

这是我根据其他问题制定的方法:

function mapToObject(object, index) {
index.split('.').reduce(function (obj, i) {
return obj[i];
});
}

另一个基于现实世界的例子是我有一个字符串数组......

[{ key: 'author.id', value: '1'}, { key: 'image.id', value: '1'}]

然后我将循环遍历这些并将它们作为对象属性添加到预定义的对象中。

let mappedRelationships = {};
let relationships = [
{
key: 'author.id',
value: 1
},
{
key: 'primaryImage.id',
value: 12
}
];

relationships.forEach((relationship) => {
mappedRelationships = {
...mappedRelationships,
// This is where I would need to do the logic for the reduce
}
});

relationshipMapped 变量的值如下:

{
author: {
attributes: {
id: 1
}
},
primaryImage: {
attributes: {
id: 12
}
}
}

最佳答案

您可以通过拆分关系数组中的key来减少并创建具有键值对的对象。

let relationships = [
{
key: 'author.id',
value: 1
},
{
key: 'primaryImage.id',
value: 12
}
];

let mappedRelationships = relationships.reduce((acc, {key, value}) => {
let [k, v] = key.split('.');
acc[k] = {attributes: {[v]: value}};
return acc
}, {});
console.log(mappedRelationships)
如果字符串有 3 个参数,则可以使用条件

let relationships = [
{
key: 'author.sites.id',
value: 1
},
{
key: 'primaryImage.id',
value: 12
}
];

let mappedRelationships = relationships.reduce((acc, { key, value }) => {
let arr = key.split('.');
let extra = arr.length > 2 ? arr.shift() : null;
let [k1, k2] = arr;
let relationships = { [k1]: { attributes: { [k2]: value } } };
return extra ? {...acc, [extra]:{relationships}} : {...acc, relationships};
}, {});
console.log(JSON.stringify(mappedRelationships))

关于Javascript |通过点符号映射到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59927178/

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