1

I have an array of objects like this:

myArr = [
    { "id": "aaa.bbb" },
    { "id": "aaa.ccc" },
    { "id": "111.222" },
    { "id": "111.333" },
]

My goal is to be able to have a new array for every part of the Id, while nesting the old array. Like this:

newArray = [
    {
      "id": "aaa",
      "children": [{ "id": "aaa.bbb" }] 
    },
    {
      "id": "aaa",
      "children": [{ "id": "aaa.ccc" }] 
    },
    {...}
]

The idea is to be able to do It with multiple substrings if there is a bigger Id

2 Answers 2

3

You could use map to iterate through the array and mutate the objects in place

myArr = [ { "id": "aaa.bbb" }, { "id": "aaa.ccc" }, { "id": "111.222" }, { "id": "111.333" }, ]
result=myArr.map((o)=>({["id"]:o.id.split(".")[0],["children"]:[o]}))
console.log(result)

alternatively you could use reduce

myArr = [ { "id": "aaa.bbb" }, { "id": "aaa.ccc" }, { "id": "111.222" }, { "id": "111.333" }, ]
result=myArr.reduce((acc,curr)=>acc=[...acc,{["id"]:curr.id.split(".")[0],["children"]:[curr]}],[])
console.log(result)

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

Comments

2

Use Array.prototype.map.

const newArray = myArr.map( function( e ) {

    const oldId = e.id;    
    const newElement = {
        id: oldId.split( '.' )[0],
        children: [ e ]
    };
    return newElement
} );

Simplified:

const newArray = myArr.map( function( e ) {
    return {
        id: e.id.split( '.' )[0],
        children: [ e ]
    };
} );

Further:

const newArray = myArr.map( e => { id: e.id.split( '.' )[0], children: [ e ] } );

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.