我有两个数组。 1 个带有标题列表,另一个带有与这些标题匹配的名称列表。
titleList
0: "CEO"
1: "CIO"
2: "CFO"
3: "CTO"
names
0: null
1: null
2: "James Dean"
3: null
0: "Paula Dean"
1: null
2: null
3: null
如何将密钥重命名为 CIO、CTO 等的名称,使其看起来像这样
CEO: "Paula Dean"
CIO: null
CFO: null
CTO: null
CEO: null
CIO: null
CFO: "James Dean"
CTO: null
我试过了
const t = resources['titles'];
const rows = resources['names'];
const map = rows;
const filteredList: any[] = [];
const MAP = skills;
for (let i = 1; i < rows.length; i++) {
const object = rows[i];
for (const key in object) {
if (MAP[key] !== null) {
object[MAP[key]] = object[key];
}
delete object[key];
}
filteredList.push(object);
}
return filteredList;
}
我猜测了您的数据结构是什么样子的,但这里有代码来创建一个对象,其中包含与rows
中的值匹配的适当键titles
;我以为你想要打字稿是因为你的typescript
标签。
const resources = {
titles: [ "CEO", "CIO", "CFO", "CTO"],
names: [null, null, "James Dean", null]
};
const titles = resources['titles'];
const rows = resources['names'];
const map: { [key: string]: string | null } = {};
titles.forEach((item, index) => map[item!] = rows[index]);
map
现在应该是类似于以下内容的对象:
{
CEO: null,
CIO: null,
CFO: "James Dean",
CTO: null
}
使用 foreach,您可以执行以下操作:
const titles: string[] = [ "CEO", "CIO", "CFO", "CTO"];
const names: (string|null)[] = [null, null, "James Dean", null];
const result: any = {};
titles.forEach((title: string, i: number) => {
result[title] = names[i];
});
console.log(result);
或者您也可以像这样使用reduce:
const titles: string[] = [ "CEO", "CIO", "CFO", "CTO"];
const names: (string|null)[] = [null, null, "James Dean", null];
const result = titles.reduce((objToReturn: any, title: string, i) => {
objToReturn[title] = names[i];
return objToReturn;
}, {});
console.log(result);
希望这对:)有所帮助