2

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
asked Apr 22, 2019 at 15:43
1
  • 1
    Object.values then .map. Commented Apr 22, 2019 at 15:50

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.