简体   繁体   中英

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.

 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); 

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) 

Simply extract the desired values from data and put them into an object formatted as you like:

 const data = [["baseball","Noun","Singular","","","","",""]]; const firstArr = data[0]; const transformedFirstObject = { [firstArr[0]]: [firstArr[1], firstArr[2]], }; console.log(transformedFirstObject); 

But it's pretty weird to have an object with only one property like that. If your data might have more than one sub-array in it and you want to turn the array of arrays into an array of objects, use map :

 const data = [ ["baseball","Noun","Singular","","","","",""], ["foo","bar","baz","","","","",""] ]; const transformed = Object.assign(...data.map(([prop, value1, value2]) => ({ [prop]: [value1, value2] }))); console.log(transformed); 

A bit simpler compared to other answers here but works as well.

 const data = [ ["baseball","Noun","Singular","","","","",""], ["baseball1","Noun1","Singular1","","","","",""], ["baseball2","Noun2","Singular2","","","","",""] ]; const obj = []; data.forEach(function(i) { let jsonObj = {}; jsonObj [i[0]] = i.slice(1).filter(x=>x !=''); obj.push(jsonObj) }); console.log(JSON.stringify(obj)) 

Just using forEach , considering multiple array elements.

 var obj = {}; var arr = [ ["baseball", "Noun", "Singular", "", "", "", "", ""], ["Test", "Test1", "Test2", "", "", "", "", ""] ]; arr.forEach(function(val, idx) { val.forEach(function(val1, idx1) { if (idx1 === 0) { obj[val1] = val.slice(1, val.length) } }) }) console.log(JSON.stringify(obj)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM