2

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.

5 Answers 5

4

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

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

Comments

4

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)

3 Comments

Lots of great answers but this one I am liking best! Thank you everyone.
Actually this one doesn't work with more than one array. @generalhenry one line answer now seems best.
@BrianBruman just enclosing the whole logic inside a forEach statement would solve your problem. That being said, the answer selected is indeed elegant :)
2

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

Comments

2

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

2 Comments

You should use j.slice(1, j.length).
Actually, j.slice(1); would be more than sufficient :)
1

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

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.