2

I have this json below:

[
  {"animal": "cat"},
  {"animal": "dog"},
  {"animal": "elephant"},
  {"vehicle": "car"},
  {"vehicle": "bike"},
  {"vehicle": "truck"},
  {"toys": "a1"},
  {"toys": "a2"},
  {"toys": "a3"}
]

My expected json response is:

[
  {"animal": "cat", "vechile": "car", "toys": "a1"},
  {"animal": "dog", "vechile": "bike", "toys": "a2"},
  {"animal": "elephant", "vechile": "truck", "toys": "a3"}
]

I tried the following program but didn't give me the expected output, I wanted to make an array where I could compare it and add accordingly:

var myGlobalArr = []
var globalObject = {}

for (var i = 0; i < mainArr.length; i++)
{
    if (Object.keys(mainArr[i])[0] == Object.keys(myGlobalArr[i])[0])
    {
        globalObject[Object.keys(mainArr[i])[0]] = globalObject[Object.values(mainArr[i])[0]]
    }
}

console.log(myGlobalArr)

HELP WOULD BE APPRECIATED!!

#EDITED:

It is going to be block of 3.

2
  • 3
    what is the rule to link the elements? Is it always blocks of 3 ? Commented Mar 8, 2019 at 4:50
  • Yep!... It is always to be 3. Commented Mar 8, 2019 at 4:54

2 Answers 2

1

You can do this using Array.reduce(). On every iteration of reduce you can check to what index of the final array put your data using the current index of the object modulus 3 (idx % 3):

const input = [
  {"animal": "cat"},
  {"animal": "dog"},
  {"animal": "elephant"},
  {"vehicle": "car"},
  {"vehicle": "bike"},
  {"vehicle": "truck"},
  {"toys": "a1"},
  {"toys": "a2"},
  {"toys": "a3"}
];

let res = input.reduce((acc, curr, idx) =>
{
    let [[k, v]] = Object.entries(curr);
    acc[idx % 3] = acc[idx % 3] || {};
    acc[idx % 3][k] = v;
    return acc;
}, [])

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Sign up to request clarification or add additional context in comments.

Comments

0

You could take a hash table which takes care of the right index of the same key for the result set.

This works for an arbitrary count of objects/properties and order, as long as the same properties are in order.

var data = [ { animal: "cat" }, { animal: "dog" }, { animal: "elephant" }, { vehicle: "car" }, { vehicle: "bike" }, { vehicle: "truck" }, { toys: "a1" }, { toys: "a2" }, { toys: "a3" }],
    indices = {},
    result = data.reduce((r, o) => {
        var key = Object.keys(o)[0];
        indices[key] = indices[key] || 0;
        Object.assign(r[indices[key]] = r[indices[key]] || {}, o);
        indices[key]++;
        return r;
    }, []);

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

Comments

Your Answer

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.