I'm dynamically calling blog categories and the number of posts that have those categories. I need an object called tabs to contain the category Titles called categoryTitle
and the number of posts called count
that have that category. I would like the final array of objects to look like this:
const tabs = [
{ categoryTitle: "blonde", count: "2"},
{ categoryTitle: "corrections", count: "2" },
{ categoryTitle: "offer", count: "1" },
{ categoryTitle: "products", count: "1" },
{ categoryTitle: "style", count: "1" },
];
How would I loop through these two objects below to create an object like above? Or should I build a class and pass the objects in ?
{blonde: 2, corrections: 2, offers: 1, products: 1, style: 1}
CodePudding user response:
Given what I can understand from the context, here's the code. If it doesn't work, please include that case in your question.
let oldObj = { blonde: 2, corrections: 2, offers: 1, products: 1, style: 1 };
const keys = Object.keys(oldObj);
const values = Object.values(oldObj);
let newObj = [];
for (i = 0; i < keys.length; i ) {
newObj.push({ categoryTitle: keys[i], count: '' values[i] });
}
console.log(newObj);
CodePudding user response:
You can simply achieve this by using Array.map() method along with Object.keys().
Demo :
const obj = {
blonde: 2,
corrections: 2,
offers: 1,
products: 1,
style: 1
};
const tabs = Object.keys(obj).map(key => {
return {
categoryTitle: key,
count: obj[key]
}
});
console.log(tabs);
CodePudding user response:
An approach was to map
over the provided object's entries
(key-value pairs) and assign key
and value
according to the OP's requirements (including the string
typecast of value
).
console.log(
Object
.entries({
blonde: 2,
corrections: 2,
offers: 1,
products: 1,
style: 1,
})
.map(([key, value]) => ({
categoryTitle: key,
count: String(value),
}))
);
.as-console-wrapper { min-height: 100%!important; top: 0; }