2

This is the (dynamic) input array:

[
 [1,"Node 1"],
 [2,"Node 2"],
 [3,"Node 3"],
 [4,"Node 4"]
//, Here the elements are going to appear
]

Can it be transformed to this?

[
 {id: 1, label: 'Node 1'},
 {id: 2, label: 'Node 2'},
 {id: 3, label: 'Node 3'},
 {id: 4, label: 'Node 4'},
 {id: 5, label: 'Node 5'}
//, Here the elements are going to be add
]
M--
33.7k12 gold badges74 silver badges115 bronze badges
asked Mar 24, 2020 at 21:12

2 Answers 2

3

I think this is the code you are looking for

const a = [
 [1,"Node 1"],
 [2,"Node 2"],
 [3,"Node 3"],
 [4,"Node 4"]
]
let objArray = []
a.forEach(element => {
 let obj = {}
 obj.id = element[0]
 obj.label = element[1]
 objArray.push(obj)
 return element
})
console.log(objArray)
Dharman
34k27 gold badges106 silver badges158 bronze badges
answered Mar 24, 2020 at 21:34
Sign up to request clarification or add additional context in comments.

5 Comments

I also built a codepen of this.
We store the array we need to transform in the variable called "a", then we declare "objArray" as the final array we want to build. We loop through the elements of "a" with the forEach method (see this). Then we declare a temporary object in which be build "{id: 1, label: 'Node 1'}". Then we to objArray.push(obj) to push, to create a new entry in our final array. Then we just console.log it.
Hi again, thanks a lot! it works on codepen perfect. I tested in Google App Script and i get the following result: [ {label=Node 1, id=1.0}, {label=Node 2, id=2.0}, {label=Node 3, id=3.0}, {label=Node 4, id=4.0} ] Do you have any idea what is the cause of the equals instead the two dots? Thanks again!
I think it's their way of showing object, using "=" instead of ":". But can I get a link of that to make sure?
To have the backup: I share the Google Spreadsheet + Google Apps Script link, and we use: var obj = JSON.stringify(objArray); to get the correct format and remplace de = with : Thanks Robert!
0

Here's a one-liner

const elements = [
 [1,"Node 1"],
 [2,"Node 2"],
 [3,"Node 3"],
 [4,"Node 4"],
 // Here the elements are going to appear
]
map(fork({ id: get(0), label: get(1) }))(elements) /*
=> [
 {id: 1, label: 'Node 1'},
 {id: 2, label: 'Node 2'},
 {id: 3, label: 'Node 3'},
 {id: 4, label: 'Node 4'},
 {id: 5, label: 'Node 5'},
]
*/

map, get, fork

answered May 25, 2020 at 22:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.