Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set First Value as Key in Javascript Array

Creating an array based off selected DataTables Rows

$('#savenlp').click(recordjourney);

function recordjourney() {
var data = table.rows(['.selected']).data().toArray();
console.log( (data) );
console.log( JSON.stringify(data) );
}

data returns

0 : (8) ["Which", "TitleCase", "QuestionWord", "", "", "", "", ""]

JSON.stringify(data) returns

[["baseball","Noun","Singular","","","","",""]]

This information is dynamically generated, so I am just looking to take the first value (in this case baseball) and turn it into something like

  "baseball": [
    "Noun",
    "Singular"
  ]

I can return the first value (the key I want using)

alert(data[0][0]);

I am much more adept in PHP but I am learning javascript/jquery more and more.

It is my understanding javascript does not have associative arrays, so I am a bit confused as to how to generate this.

like image 276
Brian Bruman Avatar asked Aug 18 '26 11:08

Brian Bruman


2 Answers

const data = [
  ["baseball","Noun","Singular","","","","",""],
  ["baseballs","Noun","","Plural","","","","",]
];
const mappedData = data.reduce((acc, row) => { acc[row.shift()] = row.filter(d => d !== ''); return acc; }, {});
console.log(mappedData);
like image 135
generalhenry Avatar answered Aug 19 '26 23:08

generalhenry


We can use object destructuring and spread operators for ease of use. In the example below, the key will be the first item and all the rest items will be placed in the newData variable

const data = [["baseball","Noun","Singular","","","","",""]];
const [key, ...newData] = data[0]
// if you want the new data to not have empty entries, simple apply the filter
const newDataFiltered = newData.filter(item => !!item)
const objWithEmpty = {[key]: newData}
const objWithoutEmpty = {[key]: newDataFiltered}


console.log(objWithEmpty, objWithoutEmpty)

For multiple arrays inside the outer array, just enclose the whole logic inside a for loop

const data = [
  ["baseball","Noun","Singular","","","","",""],
  ["baseball1","Noun1","Singular1","","","","",""],
  ["baseball2","Noun2","Singular2","","","","",""]
];
const objWithEmpty = {}
const objWithoutEmpty = {}

data.forEach((array) => {
  const [key, ...newData] = array
  // if you want the new data to not have empty entries, simple apply the filter
  const newDataFiltered = newData.filter(item => !!item)
  objWithEmpty[key] = newData
  objWithoutEmpty[key] = newDataFiltered
})

console.log(objWithEmpty, objWithoutEmpty)
like image 42
Prasanna Avatar answered Aug 19 '26 23:08

Prasanna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!