jsobjectkeys2
jsobjectkeys2

Reputation: 55

How can I format received data using Object.keys?

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

Upvotes: 3

Views: 73

Answers (2)

isherwood
isherwood

Reputation: 61105

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

Upvotes: 1

depperm
depperm

Reputation: 10756

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)

Upvotes: 3

Related Questions