0

I'm programming a small vue.js App and need to convert an array to a new one and sort them. The array of objects I get from the backend server looks like that:

var arr =
[
  {
    "id": 1,
    "name": "Name1",
    "parents": {
      "someOtherTings": "Test",
      "partentOfParent": {
        "mainId": 10
      }
    }
  },
  {
    "id": 2,
    "name": "Name2",
    "parents": {
      "someOtherTings": "Test",
      "partentOfParent": {
        "mainId": 11
      }
    }
  },
  {
    "id": 3,
    "name": "Name3",
    "parents": {
      "someOtherTings": "Test",
      "partentOfParent": {
        "mainId": 10
      }
    }
  }
]

    console.log(arr)

But I need a new array, that is sorted like that:

var newArr =
[
  {
    "mainId": 10,
    "parents": {
      "id": 1,
      "name": "Name1"
    }
  },
  {
    "mainId": 11,
    "parents": [
      {
        "id": 2,
        "name": "Name2"
      },
      {
        "id": 3,
        "name": "Name3"
      }
    ]
  }
]

What is the best way to implement this?

2 Answers 2

1

You could group the items with the help of a Map.

var array = [{ id: 1, name: "Name1", parents: { someOtherTings: "Test", partentOfParent: { mainId: 10 } } }, { id: 2, name: "Name2", parents: { someOtherTings: "Test", partentOfParent: { mainId: 11 } } }, { id: 3, name: "Name3", parents: { someOtherTings: "Test", partentOfParent: { mainId: 10 } } }],
    result = Array.from(
        array.reduce(
            (m, { id, name, parents: { partentOfParent: { mainId } } }) =>
                m.set(mainId, [...(m.get(mainId) || []), { id, name }]),
            new Map
        ),
        ([mainId, parents]) => ({ mainId, parents })
    );

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

You just need a combination of map to create a new array and then sort it based on the mainId value

var arr = [{
    "id": 1,
    "name": "Name1",
    "parents": {
      "someOtherTings": "Test",
      "partentOfParent": {
        "mainId": 10
      }
    }
  },
  {
    "id": 2,
    "name": "Name2",
    "parents": {
      "someOtherTings": "Test",
      "partentOfParent": {
        "mainId": 11
      }
    }
  },
  {
    "id": 3,
    "name": "Name3",
    "parents": {
      "someOtherTings": "Test",
      "partentOfParent": {
        "mainId": 10
      }
    }
  }
]

const newArr = arr.map(obj => ({
  mainId: obj.parents.partentOfParent.mainId,
  parents: {
    id: obj.id,
    name: obj.name
  },
})).sort((a, b) => b - a);

console.log(newArr);

1 Comment

Thank you very much for your answer. With this method I get an array for each, is it possible to merge the parents with the same mainId (like in the example)?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.