Skip to content Skip to sidebar Skip to footer

I Have An Object With Some Names As Keys, Each Key Has An Array Of Skills, I Have To Return A New Object With Skills As New Keys And Old Keys As Array

I have an object like this one const list = { jhon: ['js', 'java'], sara: ['js', 'python'], andy: ['ruby', 'js', 'java'], sean: ['python', 'ruby'] } and I have to

Solution 1:

You can easily achieve this result using Object.entries, reduce and forEach.

Since Object.entries will return an array of [key, value]. Then inside reduce you can set the property of an object (in this case acc) using forEach.

const list = {
  jhon: ["js", "java"],
  sara: ["js", "python"],
  andy: ["ruby", "js", "java"],
  sean: ["python", "ruby"],
};

const result = Object.entries(list).reduce((acc, curr) => {
  const [key, values] = curr;
  values.forEach((lang) => {
    if (acc[lang]) acc[lang].push(key);
    else acc[lang] = [key];
  });
  return acc;
}, {});

console.log(result);

You can make the above code succinct

const list = {
  jhon: ["js", "java"],
  sara: ["js", "python"],
  andy: ["ruby", "js", "java"],
  sean: ["python", "ruby"],
};

const result = Object.entries(list).reduce((acc, [key, values]) => {
  values.forEach((lang) => (acc[lang] = [...(acc[lang] ?? []), key]));
  return acc;
}, {});

console.log(result);

Solution 2:

You can iterate over Object.keys for each key, and then iterate over the array to insert values in result object i.e.

const initial = {
    jhon: ['js', 'java'],
    sara: ['js', 'python'],
    andy: ['ruby', 'js', 'java'],
    sean: ['python', 'ruby']
}

const result = {}

Object.keys(initial).forEach((person) => {
    initial[person].forEach((language) => {
        if (!Array.isArray(result[language])) {
            result[language] = []
        }
        result[language].push(person)
    })
})

console.log(result)

Solution 3:

I tried below code and get the result you want:

const list = {
        jhon: ['js', 'java'],
        sara: ['js', 'python'],
        andy: ['ruby', 'js', 'java'],
        sean: ['python', 'ruby']
    };

    functiongetPersonsByLanguegs(lang) {
        var result = [];

        for (var a in list) {
            if (list[a].includes(lang))
                result.push(a);
        }
        return result;
    }
    var newList = {};

    for (a in list) {
        if (list[a].length > 0)
            for (var i = 0; i < list[a].length; i++) {
                newList[list[a][i]] = getPersonsByLanguegs(list[a][i]);
            }
    }

enter image description here

Post a Comment for "I Have An Object With Some Names As Keys, Each Key Has An Array Of Skills, I Have To Return A New Object With Skills As New Keys And Old Keys As Array"