Adding values to 2D array with forEach - google-apps-script

I am trying to add values to a 2D array in Google Apps Script. The following code runs, but is not the desired output for the array.
function fruitList() {
var fruitArray = [['apple'], ['banana'], ['cherry']];
var newArray = [];
fruitArray.forEach(function(value) {
newArray.push([value, "name"]);
});
}
My code yields the following output:
[ [ [ 'apple' ], 'name' ], [ [ 'banana' ], 'name' ], [ [ 'cherry' ], 'name' ] ]
My desired output is:
[ [ 'apple', 'name' ], [ 'banana', 'name' ], [ 'cherry', 'name' ] ]

value is a array. Not a string/primitive value. You can use destructuring assignment to get the actual value:
fruitArray.forEach(function([/*destructure 1D array*/value]) {
newArray.push([value, "name"]);
});
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
function fruitList() {
var fruitArray = [['apple'], ['banana'], ['cherry']];
var newArray = [];
fruitArray.forEach(function([value]) {
newArray.push([value, "name"]);
});
console.info(newArray)
}
fruitList()
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Add a value:
function fruitList() {
var fruitArray = [['apple'], ['banana'], ['cherry']];
var newArray = [];
fruitArray.forEach(function(value) {
newArray.push([value[0], "name"]);
});
Logger.log(JSON.stringify(newArray))
}
Execution log
3:27:33 PM Notice Execution started
3:27:34 PM Info [["apple","name"],["banana","name"],["cherry","name"]]
3:27:34 PM Notice Execution completed

Related

How to export the api call results to a csv with the values of single response in one row?

My api response looks like below
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"2050"
]
},
{
"How much do you sleep?": [
"Ajajajsjiskskskskdkdj"
]
}
],
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"10181"
]
},
{
"How much do you sleep?": [
"Ajskossooskdncpqpqpwkdkdkskkskskksksksksks"
]
}
]
Now in react, I want to export the results to a csv. I can do it by export-to-csv but the formatting is the issue here. I want the values of each question of a single response in one row under their labels(questions). So if I have two response like above I want to have export it in two rows, not 8 as there are 8 total questions.
Here is how I want it to get exported.
I have tried so far like this but no luck.
this is my export data function
exp =()=>{
const raw = []
console.log(this.state.data[0].sbm_id)
axios.get(`/dashboard/${this.props.proj_id}/whole_sub/`)
.then(res=>{
// console.log('1')
// console.log(res.data[0][0])
// console.log('2')
for (let i =0;i<this.state.data.length;i++){
for(let j = 0;j<res.data[0].length;j++){
// let sub=[]
//res.data[i][j].ID = this.state.data[i].sbm_id
raw.push(res.data[i][j])
}
}
}
)
let curr = this.state
curr.exp = raw
this.setState({exp:curr.exp})
}
Here is my export function
rawExport=()=>{
const csvExporter = new ExportToCsv(optionsExp);
csvExporter.generateCsv(this.state.exp);
}
First step is to flatten the initial nested array to get a homogeneously shaped array, then you keep on reducing it further.
const data = [
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"2050"
]
},
{
"How much do you sleep?": [
"Ajajajsjiskskskskdkdj"
]
}
],
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"10181"
]
},
{
"How much do you sleep?": [
"Ajskossooskdncpqpqpwkdkdkskkskskksksksksks"
]
}
]
];
const flattenArray = (arr) => [].concat.apply([], arr);
// Flatten the initial array
const flattenedArray = flattenArray(data);
// Keep on reducing the flattened array into an object
var res = flattenedArray.reduce((acc, curr) => {
const [key, val] = flattenArray(Object.entries(curr));
if (!acc[key]) {
acc[key] = [].concat(val);
} else {
val.forEach(x => {
if (!acc[key].includes(x)) {
acc[key].push(x);
}
});
}
return acc;
}, {});
console.log(res);

Getting json object data with react

I am attempting to pull data out of json like this, which is imported as "values"
{
"content": {
"person": [
{
"name": "Test"
"age" : "24:
}
]
}
}
I am using .map like below but getting the error .default.map is not a function I believe it is because i have objects not arrays, i've tried a bunch of stuff including object.keys but i'm getting errors all over the place, any direction would be appreciated.
import values from './sample.json'
const vals = values.map((myval, index) => {
const items = person.items.map((item, i) => {
return (
<div>{item.name}</div>
)
})
return (
<div>{items}</div>
)
})
I think your data and code have some errors. But after fixing those and also changing the name from 'person' to 'people' if that's what you are after, here's the code that does what you are trying to do:
var data = {
content: {
people: [
{
name: "Test",
age: 24,
},
{
name: "Foo",
age: 25,
},
],
},
};
var App = React.createClass({
render: function () {
var people = data.content.people.map(function (person) {
return <div>{person.name}</div>;
});
return <div>{people}</div>;
},
});
ReactDOM.render(<App />, document.getElementById("app"));
And here's the JSBin for that: https://jsbin.com/coyalec/2/edit?html,js,output
Update: I'm updating the answer with more detailed example. It now deals with data more generically, like it doesn't assume what are the entries of 'contents' and such, but it knows that each type like 'people' or 'pets' are an array.
var data = {
content: {
people: [
{
name: "Test",
age: 24,
},
{
name: "Foo",
age: 25,
},
],
pets: [
{
name: "Sweety",
age: 3,
},
{
name: "Kitty",
age: 5,
},
],
},
};
var App = React.createClass({
render: function () {
// Get the keys in data.content. This will return ['people', 'pets']
var contentKeys = Object.keys(data.content);
// Now start iterating through these keys and use those keys to
// retrieve the underlying arrays and then extract the name field
var allNames = contentKeys.map((t) =>
data.content[t].map((e) => <div>{e.name}</div>)
);
return <div>{allNames}</div>;
},
});
ReactDOM.render(<App />, document.getElementById("app"));
And here's the latest JSBin: https://jsbin.com/coyalec/4/edit?html,js,output

How to format the JSON object key/value pair

I am new to nodejs, right now I am able to fetch the data from the database and display as REST API which is of key/value pair. My output looks like as shown below
[{"id":"793","actionname":"test_bsc_interface","actionid":"100"}].
But I need to format as
{ "header" : [id,actionname,actionid],
"values" : [793 ,test_bsc_interface,100] ],}.
I tried with JSON.stringfy and checked few website but it's not working.
Could any one please help me through which link I should go through or approach.
The easy way to do it is to use underscore or lodash module to format it:
var _ = require('lodash');
var data = [{"id":"793","actionname":"test_bsc_interface","actionid":"100"}];
var result = _.map(data, function(o) {
return {headers: _.keys(o), values : _.values(o)}
});
console.dir(result);
Output is:
[
{
headers: [ 'id', 'actionname', 'actionid' ],
values: [ '793', 'test_bsc_interface', '100' ]
}
]
To get the result you want, just do result[0]
Note that I use _.map() instead of data[0] because this will work for the array (your array result from the query) that has more than 1 item.
Revised answer according to your comment (1 header line and all value lines in an array):
var _ = require('lodash');
var data = [
{ id: '714', actionname: 'test_bsc_interface', actionid: '100' },
{ id: '715', actionname: 'list_all_available_interfaces', actionid: '103' },
{ id: '716', actionname: 'check_tt', actionid: '101' }
];
var result;
if (_.size(data) > 0) {
result = {
headers: _.keys(data[0]),
values: _.map(data, function(o) {
return _.values(o);
})
};
}
console.dir(result);
and the output is:
{
headers: [ 'id', 'actionname', 'actionid' ],
values: [
[ '714', 'test_bsc_interface', '100' ],
[ '715', 'list_all_available_interfaces', '103' ],
[ '716', 'check_tt', '101' ]
]
}

Reorder JSON by value, showing a,b,c,a,b,c

I have some JSON that is in the below format. I want to have a script that rearranges this so that it's ordered by preference, but with alternating values. For instance, showing a,b,c,a,b,c. Can anyone help with this?
[
{
"name" : "Tim",
"preference" : "b"
},
{
"name" : "Tom",
"preference" : "b"
},
{
"name" : "Steve",
"preference" : "a"
},
{
"name" : "Rick",
"preference" : "a"
},
{
"name" : "Nile",
"preference" : "c"
},
{
"name" : "James",
"preference" : "c"
}
]
Underscore provides utilities suited to this task.
First, group your input by the preference field:
var groups = _.groupBy(input, 'preference');
Then convert this into an array of arrays:
var arrays = _.values(groups);
Then, "zip" the groups:
var result = _.zip.apply(null, arrays);
In one line:
var result = _.zip.apply(null, _.values(_.groupBy(input, 'preference')));
Non-Underscore version
If you can't/don't want to use Underscore, then you'll have to write your own versions of groupBy and zip:
function groupBy(array, prop) {
var result = {};
for (var i = 0; i < array.length; i++) {
var entry = array[i];
var val = entry[prop];
if (!result[val]) result[val] = [];
result[val].push(entry);
}
return result;
}
Either this or Underscore's _.groupBy will transform your input into
{
b: [ { name: 'Tim', preference: 'b' }, ... ],
a: [ { name: 'Rick', preference: 'a' }, ... ]
}
To get an array of the arrays:
function values(obj) {
return Object.keys(obj) . sort() . map(function(key) { return obj[key]; });
}
This will result in
[
[ { name: 'Tim', preference: 'b' }, ... ],
[ { name: 'Rick', preference: 'a' }, ... ]
]
Then for zip:
function zip(arrays) {
var result = [];
var n = 0;
var more = true;
var array;
while (more) {
more = false;
for (var i = 0; i < arrays.length; i++) {
array = arrays[i];
if (n < array.length) {
more = true;
result.push(array[n]);
}
}
n++;
}
return result;
}
Note: this implementation of zip takes an array of arrays as a parameter, unlike Underscore's version, which takes the arrays as individual parameters.
Then
zip(values(groupBy(input, 'preference')))

Unable to display data from json.net

Can anyone help solve this problem, no matter what i try i cannot display the data on webpage, i can put a breakpoints at JObject o = JObject.Parse(ws); and see the data, but every attempt i have tried results in a different error.I'm trying to do is get the areaName and country.
I have tried the examples from: http://james.newtonking.com/projects/json/help/ and http://forums.asp.net/t/1780822.aspx/1?How+to+traverse+in+json+ with no luck
Any help would be appreciated.
George
My code is below:
string ws = #"{ ""search_api"": { ""result"": [ { ""areaName"": [ {""value"": ""London"" } ], ""country"": [ {""value"": ""United Kingdom"" } ], ""latitude"": ""51.517"", ""longitude"": ""-0.106"", ""population"": ""7421228"", ""region"": [ {""value"": ""City Of London, Greater London"" } ], ""timezone"": [ {""offset"": ""1.0"" } ], ""weatherUrl"": [ {""value"": ""http:\/\/www.worldweatheronline.com\/London-weather\/City-of-London-Greater-London\/GB.aspx"" } ] }, { ""areaName"": [ {""value"": ""London"" } ], ""country"": [ {""value"": ""Canada"" } ], ""latitude"": ""42.983"", ""longitude"": ""-81.250"", ""population"": ""346774"", ""region"": [ {""value"": ""Ontario"" } ], ""timezone"": [ {""offset"": ""-4.0"" } ], ""weatherUrl"": [ {""value"": ""http:\/\/www.worldweatheronline.com\/London-weather\/Ontario\/CA.aspx"" } ] } ] }}";
JObject o = JObject.Parse(ws);
var weatherCity = o["areaName"][0]["value"];
ViewBag.WeatherSearch = weatherCity.ToString();
//var weatherCity = o["search_api"][0]["result"]["areaName"]["value"];
// JArray arr = (JArray)o.SelectToken("search_api");
// JObject cityTown = (JObject)arr[0].SelectToken("result").SelectToken("areaName");
// var weatherCity = cityTown.SelectToken("value");
// IList<string> WeatherCity = o.SelectToken("result").Select(s => (string)s).ToList();
//string WeatherCity = (string)o.SelectToken("result[0].areaName[0].value");
//IList<string> WeatherCities = o["result"].Select(m => (string)m.SelectToken("areaName[0].value")).ToList();
How about something like:
var weatherCity = o["search_api"]["result"][0]["areaName"][0]["value"];
o represents the root, so you can't skip any nodes.