kLezer
kLezer

Reputation: 221

how i can merge nested array with in a new object with ramda?

There is an object that holds variables related to the UI.

const data = [
  { color: [{ primary: "#444", secondary: "#dede", light: "#fff" }] },
  { size: [12,14,16,18,20] },
  ...
];

I want to make this object a single array like:

const UI = [
    { colorPrimary: "#444" },
    { colorSecondary: "#dede" },
    { colorLight: "#fff" },
    { size0: 12 },
    { size1: 14 },
    { size2: 16 },
    { size3: 18 },
    { size4: 20 },
    ...
];

How can I do this with ramda ?

Upvotes: 0

Views: 1128

Answers (1)

Scott Sauyet
Scott Sauyet

Reputation: 50797

I don't have a clean way to do it with the data as supplied because of the reason expressed in my comment:

How would you distinguish between a property like color, where you seem to ignore the array holding the data, and one like size, where the array indices become part of the keys?

But with just a minor tweak to your data, to this:

const data = [
  { color: { primary: "#444", secondary: "#dede", light: "#fff" } },
  { size: [12,14,16,18,20] },
];

It's reasonably straightforward:

const initialCap = str => toUpper(head(str)) + tail(str);

const collectProps = pipe(
  map(map(toPairs)),
  apply(merge),
  mapObjIndexed((pairs, key) => map(
    pair => objOf(key + initialCap(pair[0]), pair[1]), pairs
  )),
  values,
  apply(concat)
);

collectProps(data);

You can see this in action on the Ramda REPL.

I don't know anything about the source of your data, so I have no idea if this is at all possible for you to manage. But if you can, this looks like it should work.

Upvotes: 1

Related Questions