Home > Net >  How can I format received data using Object.keys?
How can I format received data using Object.keys?

Time:01-25

I have this data:

const langs = {
    en: ['One', 'description'],
    pl: ['Jeden', 'opis'],
};

And I'm trying to parse it into this format:

const formattedData = {
    name: {
        en: "One",
        pl: "Jeden",
    },
    description: {
        en: "description",
        pl: "opis",
    }
};

I tried to do something like this:

const langs = {
  en: ['One', 'description'],
  pl: ['Jeden', 'opis'],
};

const val = Object.keys(langs).map(item => ({
  [item]: langs[item][0]
}))

console.log(val);

CodePudding user response:

I'd use Object.entries to get key, value pair and then add an object which has name and description keys already defined

const langs = {
  en: ['One', 'description'],
  pl: ['Jeden', 'opis'],
};
let val = {name:{}, description:{}}
Object.entries(langs).forEach(([key,v])=>{
  val.name[key]=v[0]
  val.description[key]=v[1]
})
console.log(val)

CodePudding user response:

You can use a for loop and object destructuring to parse the data into the desired format.

const langs = {
    en: ['One', 'description'],
    pl: ['Jeden', 'opis'],
};

const formattedData = {
  name: {},
  description: {},
};

Object.entries(langs).forEach(([lang, [name, description]]) => {
  formattedData.name[lang] = name;
  formattedData.description[lang] = description;
});

console.log(formattedData)

This uses the Object.entries method to get an array of key-value pairs for the langs object, where each pair is a [lang, [name, description]] array. The forEach method is then used to iterate over each pair, destructuring the values from each pair and using them to add properties to the formattedData object.

CodePudding user response:

Here's how you could do it with Object.keys, as asked. You may need to create the target object structure in advance (or at least it's more readable to do so).

const langs = {
  en: ['One', 'description'],
  pl: ['Jeden', 'opis'],
};
let newObj = {
  name: {},
  description: {}
};

Object.keys(langs).forEach(item => {
  newObj.name[item] = langs[item][0];
  newObj.description[item] = langs[item][1];
});

console.log(newObj);

  • Related