Terrance Jackson
Terrance Jackson

Reputation: 1069

Typescript renaming keys in array without hardcoding?

I have two arrays. 1 with a list of titles the other with a list of names that will match these titles.

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

How can I rename the keys to the names of CIO, CTO etc so it looks like this

CEO: "Paula Dean"
CIO: null
CFO: null
CTO: null

CEO: null
CIO: null
CFO: "James Dean"
CTO: null

I have tried

 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;
  }

Upvotes: 0

Views: 129

Answers (2)

Mohammed Amir Ansari
Mohammed Amir Ansari

Reputation: 2401

With foreach you can do something like:

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);

or you can also use reduce like:

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);

Hope this helps :)

Upvotes: 0

Justin Collins
Justin Collins

Reputation: 350

I took a guess at what your data structure looks like but here is code to create an object with the appropriate keys from titles matching the values from rows; I assumed you wanted typescript because of your typescript tag.

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 should now be object similar to:

{
    CEO: null,
    CIO: null,
    CFO: "James Dean",
    CTO: null
}

Upvotes: 1

Related Questions