0

problem is that. I have one json object, lets assume it's look like that:

{
  "first": {
    "arg": [
        "val1",
        "val2"
    ]
  },
  "second": {
    "arg1": [
        "val11",
        "val12"
    ],
    "arg2": [
        "val21",
        "val22"
    ]
  }
}

And now I need to make from it two objects , looking like this:

{
  "first": {
    "arg":"val1"
  },
  "second": {
    "arg1":"val11",
    "arg2":"val21"
  }
}

And second one like this:

{
  "first": {
    "arg":"val2"
  },
  "second": {
    "arg1":"val12",
    "arg2":"val22"
  }
}

There is easy way to make them like that?

2
  • 1
    Well there are ways to do it, they may or may not be easy in your estimation, but what has your research, if any, revealed, and what attempt(s) have you made?
    – Dexygen
    Dec 5, 2019 at 14:24
  • 3
    seems that the requirement is to have multiple objects from an array by its indexes. First object contains elements that are at index 0. The second at index 1. So, just go through the object, access the elements in their arrays at the given index and put it the new object. You can do it yourself. Please try it.
    – KarelG
    Dec 5, 2019 at 14:25

1 Answer 1

1

You could map the most inner values or the mapped valued from the recursive call and assign the value to an object by respecting the index.

function map(object) {
    return Object
        .entries(object)
        .reduce((r, [k, v]) => {
            (Array.isArray(v) ? v : map(v)).forEach((w, i) => {
                r[i] = r[i] || {};
                r[i][k] = w;
            });
            return r;
        }, []);
}

var data = { first: { arg: ["val1", "val2"] }, second: { arg1: ["val11", "val12"], arg2: ["val21", "val22"] } },
    result = map(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Not the answer you're looking for? Browse other questions tagged or ask your own question.