我正在构建一个typecirpt字典,像这样:
const skills = x
.map(y => y.skills)
.flat(1)
.map(z => {
return { [z.id]: { skill: z } };
});
这是我通过上面的代码获得的数组:
{ 7ff2c668-0e86-418a-a962-4958262ee337: {skill: {…}} }
{ c6846331-2e11-45d6-ab8d-306c956332fc: {skill: {…}} }
{ 0fc0cb61-f44d-4fd0-afd1-18506380b55e: {skill: {…}} }
{ 36dc0b74-84ee-4be2-a91c-0a91b4576a21: {skill: {…}} }
现在的问题是我无法通过按键访问字典:
const id = '7ff2c668-0e86-418a-a962-4958262ee337';
const one = myArr.find(x => x === id); // returns undefined
const two = myArr[id]; // returns undefined
有什么办法解决吗?
答案 0 :(得分:1)
您可以使用Object.keys()
来获取每个对象的密钥。在您的情况下,每个对象的键都是其ID。然后使用它来检查它是否等于x
(您搜索ID)。
请参见以下示例:
const myArr = [
{"7ff2c668-0e86-418a-a962-4958262ee337": {skill: 1}},
{"c6846331-2e11-45d6-ab8d-306c956332fc": {skill: 2}},
{"0fc0cb61-f44d-4fd0-afd1-18506380b55e": {skill: 3}},
{"36dc0b74-84ee-4be2-a91c-0a91b4576a21": {skill: 4}}],
id = "36dc0b74-84ee-4be2-a91c-0a91b4576a21",
one = myArr.findIndex(x => Object.keys(x)[0] === id); // the index of the object which has the search id as its key.
myArr[one] = {newKey: "newValue"}; // set the index found to have a new object
console.log(myArr);
答案 1 :(得分:1)
您现在正在创建对象数组。我建议您改为创建一个对象,以ID作为键
示例:
const skills = x
.map(y => y.skills)
.flat(1)
.reduce((acc, z) => {
acc[z.id] = z;
return acc;
}, {});
您的myArr
看起来像:
{
'7ff2c668-0e86-418a-a962-4958262ee337': {...}
'c6846331-2e11-45d6-ab8d-306c956332fc': {...},
'0fc0cb61-f44d-4fd0-afd1-18506380b55e': {...},
'36dc0b74-84ee-4be2-a91c-0a91b4576a21': {...}
}
然后您可以按预期的方式访问它:
const skill = myArr['7ff2c668-0e86-418a-a962-4958262ee337'];
答案 2 :(得分:1)
利用可以提供帮助的地图
Map
是ES6中引入的新数据结构。它允许您存储类似于其他编程语言的键值对,例如Java,C#。
let map = new Map();
const skills = x
.map(y => y.skills)
.flat(1)
.map(z => {
map.set(z.Id, { skill: z })
return map;
});
//Get entries
amp.get("7ff2c668-0e86-418a-a962-4958262ee337"); //40
//Check entry is present or not
map.has("7ff2c668-0e86-418a-a962-4958262ee337"); //true