我正在构建一个这样的 typescirpt 字典:
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
有什么解决办法吗?
最佳答案
您可以使用 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);
关于javascript - typescript 字典有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54704093/