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
2 Answers 2
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)
answered Mar 24, 2020 at 21:34
Robert Feduș
3112 silver badges17 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Robert Feduș
I also built a codepen of this.
Robert Feduș
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.
Mario IR
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!
Robert Feduș
I think it's their way of showing object, using "=" instead of ":". But can I get a link of that to make sure?
Mario IR
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!
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'},
]
*/
answered May 25, 2020 at 22:42
richytong
2,5021 gold badge14 silver badges24 bronze badges
Comments
lang-js