How to turn an object from this one:
{
"x1": {
"src": "https://....png",
"webp": "https://....webp"
},
"x2": {
"src": "https://....png",
"webp": "https://....webp"
}
}
to this one:
[
{
srcSet: 'https://....webp 1x, https://....webp 2x'
},
{
srcSet: 'https://....png 1x, https://....png 2x'
}
]
I'm stuck with it, tried different object methods but always coming up with the same code which doesn't work as I expect it.
Jason Aller
3,66028 gold badges43 silver badges40 bronze badges
2 Answers 2
You could get the entries and then map the values with keys for each index.
var data = { x1: { src: "https://....png", webp: "https://....webp" }, x2: { src: "https://....png", webp: "https://....webp" } },
result = Object
.entries(data)
.reduce((r, [k, o]) => Object
.values(o)
.map((p, i) => ({ srcSet: [].concat(r[i] && r[i].srcSet || [], `${p} ${k}`).join(', ') })),
[]
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
answered Apr 22, 2019 at 15:52
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Here's a one-liner approach:
const obj = {
"x1": {
"src": "https://....png",
"webp": "https://....webp"
},
"x2": {
"src": "https://....png",
"webp": "https://....webp"
}
}
// one-liner
const result = Object
.entries(obj)
.map(r => ({ srcSet: Object.values(r[1]).map(v => [v, r[0]].join(' ')).join(',') }));
console.log(result);
answered Apr 22, 2019 at 16:20
Amit Baranes
8,2222 gold badges40 silver badges62 bronze badges
Comments
lang-js
Object.valuesthen.map.