5

I stuggle a lot with data I get from an API:

This is the way the data gets returned, the amout of arrays differs.

const objData = {
    arr1: [1,2,3],
    arr2: [1,2,1],
    arr3: [2,1,2],
    arr4: ["a","b", "c"]
}

This is the way it SHOULD look

const desired = [
    {a: 1, b: 1, c: 2, d: "a"},
    {a: 2, b: 2, c: 1, d: "b"},
    {a: 2, b: 1, c: 2, d: "c"}
]

This gives me the desired result, but it is not dymanic, since I have to provide the names of the arrays, and the amount of arrays in the object is not allowed to change.

const DataObj = []

for (let i = 0; i < objData.arr1.length; i++) {
    const objX = {
        a: objData.arr1[i],
        b: objData.arr2[i],
        c: objData.arr3[i],
        d: objData.arr4[i],
    }
    DataObj.push(objX)
}

Can anybody help me to solve this? How can I make this independent from the names of the arrays and the amount of arrays in the dataset?

4
  • 4
    is desired correct? Commented Aug 28, 2020 at 7:50
  • How you are deciding the key for {a: 1, b: 1, c: 2, d: "a"}, like a, b, c and d. Is there any logic for it ? Commented Aug 28, 2020 at 7:54
  • 2
    Pretty sure the second row should be [2,2,1, "b"] Commented Aug 28, 2020 at 7:54
  • you are right, did not see this. Commented Aug 28, 2020 at 7:57

2 Answers 2

3

You could map the arrays with new objects.

const
    objData = { arr1: [1, 2, 3], arr2: [1, 2, 3], arr3: [2, 1, 2], arr4: ["a", "b", "c"] },
    keys = { arr1: 'a', arr2: 'b', arr3: 'c', arr4: 'd' },
    result = Object
        .entries(objData)
        .reduce((r, [key, array]) => array.map((v, i) => ({ ...r[i], [keys[key]]: v  })), []);
        
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

0

Non functional approach, use integers to get your letters

const objData = {
  arr1: [1, 2, 3, 5],
  arr2: [1, 2, 1, 4],
  arr3: [2, 1, 2, 3],
  arr4: ["a", "b", "c", "d"]
}



const len = Object.values(objData)[0].length;
let cnt = 97;
let newObj = {};
const list = [];

for (let i = 0; i < len; i++) {
  for (let key in objData) {
    newObj[String.fromCharCode(cnt)] = objData[key][i];
    ++cnt
  }
  list.push(newObj);
  cnt = 97;
  newObj = {};
}

console.log(list)

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.