I have variable that is containing some sort of JSON data,
var blogData = [
{
"blogTitle":"Bangladesh",
"imagePath":"/img/blog/bangladesh.jpg"
},{
"blogTitle":"India",
"imagePath":"/img/blog/india.jpg"
}
]
What I want a new array titleFilter like:
var titleFilter = [
Bangladesh : "/img/blog/bangladesh.jpg",
India : "/img/blog/india.jpg"
]
So, for this purpose, I have tried this:
var titleFilter = [];
for (var i = 0; i < blogData.length; i++) {
titleFilter[blogData[i].blogTitle] = blogData[i].imagePath;
}
The problem is, I am getting the titleFilter array as:
var titleFilter = [
Bangladesh : "",
India : ""
]
It would be great if someone help me regarding this problem.
Try this:
const blogData = [
{
"blogTitle":"Bangladesh",
"imagePath":"/img/blog/bangladesh.jpg"
},{
"blogTitle":"India",
"imagePath":"/img/blog/india.jpg"
}
];
const result = blogData.reduce((acc, ele)=> (acc[ele.blogTitle] = ele.imagePath , acc),{});
console.log(result);
I am not sure what you are looking for but you can use map like this to achieve it.
var map = new Object(); // or var map = {};
map[blogData[i].blogTitle] = blogData[i].imagePath;
var blogData = [
{
"blogTitle":"Bangladesh",
"imagePath":"/img/blog/bangladesh.jpg"
},
{
"blogTitle":"India",
"imagePath":"/img/blog/india.jpg"
}
]
var titleFilter = {}
blogData.forEach( x => titleFilter[x.blogTitle] = x.imagePath )
Use this code, and you will get the desired result in titleFilter
Related
{ "data": [ {"firstName": "Achmad"}, {"lastName": "a"} ] } and this my script var body = request.body;for(var i = 0;i < body.data.length;i++){var obj = body.data[i];var keyes = Object.keys(obj);} the problem response from var keyes = Object.keys(obj); is list like this [ 'firstName' ] [ 'lastName' ] i'm wanna like this ['firstName', 'lastName']
Thanks before.
Assuming each of the arrays are elements of a parent array, one way you could achieve this is by using Array.prototype.reduce:
const flat = [
["aku"],
["dia"],
["ia"]
].reduce((accum, el) => accum.concat(el), [])
console.log(flat);
EDITED: You could concat each item of your array :
const body = {
"data": [
{"firstName": "Achmad"},
{"lastName": "a"}
]
};
let result = [];
for (item of body.data) {
result = result.concat(Object.keys(item));
}
console.log(result); // -> ['firstName', 'lastName']
Maybe you want to do something like this
var body = request.body;
var keyes = [];
for(var i = 0; i < body.data.length; i++){
var obj = body.data[i];
keyes.push( Object.keys(obj) );
}
I am trying to teach myself some AppScript/Javascript. As an exercise, I am want to generate the following JSON object
[
{
"config_type": "City Details",
"config_data": [
{
"city_type": "MAJOR_CITY",
"city_data": [
{
"city_name": "BIGFOOLA",
"monetary_data": [
{
"currency_data": [
{
"dollars": 1000
}
]
}
]
}
]
}
]
}
]
I want to be able to enter only few details like "City Details", "MAJOR_CITY", and the dollar value - 1000 in a Google Sheet. The script should be able to generate the above JSON.
So I started by creating the names of all the Arrays and Objects in one row. In front of the the arrays, there was a blank cell and in front of the object the value. The Sheet looks like this
A B
config_type City Details
config_data
city_type MAJOR_CITY
city_data
city_name BIGFOOLA
monetary_data
currency_data
dollars 1000
I am able to get all of the details in a single object, but struggling to nest them under each other. How do I go about this?
Edit :Here is what I have for now
function doGet(){
var result={}
var rewardSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CITY")
var reward_data = rewardSheet.getRange("A1:B13").getValues();
result = getJsonArrayFromData(reward_data);
return ContentService.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON)
}
function getJsonArrayFromData(data)
{
var column_headers = data[0];
var col_len = column_headers.length;
var row = [];
var reward_obj = [];
var config_obj = {};
var config_type = {};
var config_data = [];
var reward_type = {};
var reward_data = [];
var reward_name = {};
var reward_data_2 = [];
var currency_data = [];
var curreny_obj = {};
var rewardSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CITY")
var row_items = rewardSheet.getRange(1,1,data.length,1).getValues();
//Logger.log(row_items);
for(var i=0;i<data.length;i++){
row = data [i];
config_type ={};
reward_type[config_type]={};
reward_name[reward_type]={};
//Logger.log(row);
for(var r=0;r<row.length;r++)
{
config_type[row[r]] = row[r+1];
reward_type[row[r]] = row[r+1];
reward_name[row[r]] = row[r+1];
}
config_data.push(config_type,reward_type,reward_name);
//reward_data.push(reward_name);
reward_obj = config_data;
}
Logger.log(reward_obj);
return reward_obj;
}
Ps: I know the JSON is messy, but its just to understand and teach myself.
You hard-coded a bunch of property names as variables; this is not a good approach.
Here is how one can do this. The variable output holds the object we'll return at the end, while currentObject points to the object that is due to be filled next. When it comes to filling it, we either have a scalar value data[i][1] to put in, or we don't, in which case a new object is created and becomes the new currentObject.
function formJSON() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("CITY");
var data = sheet.getDataRange().getValues();
var currentObject = {};
var output = [currentObject]; // or just currentObject
for (var i = 0; i < data.length; i++) {
if (data[i][1]) {
currentObject[data[i][0]] = data[i][1];
}
else {
var newObject = {};
currentObject[data[i][0]] = [newObject]; // or just newObject
currentObject = newObject;
}
}
Logger.log(JSON.stringify(output));
}
The output is
[{"config_type":"City Details","config_data":[{"city_type":"MAJOR_CITY","city_data":[{"city_name":"BIGFOOLA","monetary_data":[{"currency_data":[{"dollars":1000}]}]}]}]}]
or, in beautified form,
[{
"config_type": "City Details",
"config_data": [{
"city_type": "MAJOR_CITY",
"city_data": [{
"city_name": "BIGFOOLA",
"monetary_data": [{
"currency_data": [{
"dollars": 1000
}]
}]
}]
}]
}]
Incidentally, I don't see why you wanted to put every object in an array. A property can be another object. Removing square brackets on the commented lines we would get
{
"config_type": "City Details",
"config_data": {
"city_type": "MAJOR_CITY",
"city_data": {
"city_name": "BIGFOOLA",
"monetary_data": {
"currency_data": {
"dollars": 1000
}
}
}
}
}
I have the following array:
var sampleArray = [
"CONTAINER",
"BODY",
"NEWS",
"TITLE"];
I want to have the following output:
var desiredOutput = [{
"CONTAINER": [{
"BODY": [{
"NEWS": [{
"TITLE": []
}]
}]
}]
}];
How can I achieve this in JavaScript?
Already tried with recursive loop, but it does not work, gives me undefined.
dataChange(sampleArray);
function dataChange(data) {
for (var i = 0; i < data.length; i++) {
changeTheArray[data[i]] = data[i + 1];
data.splice(i, 1);
dataChange(changeTheArray[data[i]]);
}
}
Thanks
This does what you're asking for, in one line, and with no additional variables:
let desiredOutput = sampleArray.reduceRight((obj, key) => [ { [key]: obj } ], []);
The reduceRight call, starting from the right hand end of the array, progressively accumulates the current data (seeded with the initial value of []) as the value of the single key in a new object { [key] : _value_ } where that object is itself the single entry in an array [ ... ].
This will do it:
const sampleArray = ["CONTAINER", "BODY", "NEWS", "TITLE"];
const data = []; // Starting element.
let current = data; // Pointer to the current element in the loop
sampleArray.forEach(key => { // For every entry, named `key` in `sampleArray`,
const next = []; // New array
current.push({[key]: next}); // Add `{key: []}` to the current array,
current = next; // Move the pointer to the array we just added.
});
console.log(data);
{[key]: next} is relatively new syntax. They're computed property names.
This:
const a = 'foo';
const b = {[a]: 'bar'};
Is similar to:
const a = 'foo';
const b = {};
b[a] = 'bar';
You could re-write the forEach as a one-liner:
const sampleArray = ["CONTAINER", "BODY", "NEWS", "TITLE"];
const data = []; // Starting element.
let current = data; // Pointer to the current element in the loop
sampleArray.forEach(key => current.push({[key]: current = [] }));
console.log(data);
This current.push works a little counter-intuitively:
Construct a new element to push. This assigns a new value to current.
Push the new element to the reference .push was called on.
That reference is the value of current before current = [].
Hi i made a little demo :
var sampleArray = [
"CONTAINER",
"BODY",
"NEWS",
"TITLE"
],
generateArray = [],
tmp = null;
for(var i = 0; i < sampleArray.length; i++) {
if(tmp===null){
generateArray[sampleArray[i]] = {};
tmp = generateArray[sampleArray[i]];
}else{
tmp[sampleArray[i]] = {};
tmp = tmp[sampleArray[i]];
}
}
console.log(generateArray);
I have the following array:
var sampleArray = [
"CONTAINER",
"BODY",
"NEWS",
"TITLE"];
I want to have the following output:
var desiredOutput = [{
"CONTAINER": [{
"BODY": [{
"NEWS": [{
"TITLE": []
}]
}]
}]
}];
How can I achieve this in JavaScript?
Already tried with recursive loop, but it does not work, gives me undefined.
dataChange(sampleArray);
function dataChange(data) {
for (var i = 0; i < data.length; i++) {
changeTheArray[data[i]] = data[i + 1];
data.splice(i, 1);
dataChange(changeTheArray[data[i]]);
}
}
Thanks
This does what you're asking for, in one line, and with no additional variables:
let desiredOutput = sampleArray.reduceRight((obj, key) => [ { [key]: obj } ], []);
The reduceRight call, starting from the right hand end of the array, progressively accumulates the current data (seeded with the initial value of []) as the value of the single key in a new object { [key] : _value_ } where that object is itself the single entry in an array [ ... ].
This will do it:
const sampleArray = ["CONTAINER", "BODY", "NEWS", "TITLE"];
const data = []; // Starting element.
let current = data; // Pointer to the current element in the loop
sampleArray.forEach(key => { // For every entry, named `key` in `sampleArray`,
const next = []; // New array
current.push({[key]: next}); // Add `{key: []}` to the current array,
current = next; // Move the pointer to the array we just added.
});
console.log(data);
{[key]: next} is relatively new syntax. They're computed property names.
This:
const a = 'foo';
const b = {[a]: 'bar'};
Is similar to:
const a = 'foo';
const b = {};
b[a] = 'bar';
You could re-write the forEach as a one-liner:
const sampleArray = ["CONTAINER", "BODY", "NEWS", "TITLE"];
const data = []; // Starting element.
let current = data; // Pointer to the current element in the loop
sampleArray.forEach(key => current.push({[key]: current = [] }));
console.log(data);
This current.push works a little counter-intuitively:
Construct a new element to push. This assigns a new value to current.
Push the new element to the reference .push was called on.
That reference is the value of current before current = [].
Hi i made a little demo :
var sampleArray = [
"CONTAINER",
"BODY",
"NEWS",
"TITLE"
],
generateArray = [],
tmp = null;
for(var i = 0; i < sampleArray.length; i++) {
if(tmp===null){
generateArray[sampleArray[i]] = {};
tmp = generateArray[sampleArray[i]];
}else{
tmp[sampleArray[i]] = {};
tmp = tmp[sampleArray[i]];
}
}
console.log(generateArray);
var arr = [
{level:0,name:"greg"},
{level:0,name:"Math"},
{level:0,name:"greg"}
];
I have tried the following:
function removeDuplicates:(dataObject){
self.dataObjectArr = Object.keys(dataObject).map(function(key){
return dataObject[key];
});
for(var i= 0; i < self.dataObjectArr.length; i++ ){
self.dataObjectArr[i]['name'] = self.dataObjectArr[i];
self.uniqArr = new Array();
for(var key in self.dataObjectArr){
self.uniqArr.push(self.dataObjectArr[key]);
}
}
self.uniqObject = DataMixin.toObject(self.uniqArr);
return self.uniqObject;
}
But I get error saying: Uncaught TypeError: Converting circular structure to JSON.
You should push the name to an array or a set and check the same in the following..
var arr = [{
level: 0,
name: "greg"
}, {
level: 0,
name: "Math"
}, {
level: 0,
name: "greg"
}]
function removeDuplicates(arr) {
var temp = []
return arr.filter(function(el) {
if (temp.indexOf(el.name) < 0) {
temp.push(el.name)
return true
}
})
}
console.log(removeDuplicates(arr))
Here's a generic "uniquify" function:
function uniqBy(a, key) {
var seen = new Set();
return a.filter(item => {
var k = key(item);
return !seen.has(k) && seen.add(k)
});
}
///
var arr = [
{level:0,name:"greg"},
{level:0,name:"greg"},
{level:0,name:"joe"},
{level:0,name:Math},
{level:0,name:"greg"},
{level:0,name:"greg"},
{level:0,name:Math},
{level:0,name:"greg"}
];
uniq = uniqBy(arr, x => x.name);
console.log(uniq);
See here for the in-depth discussion.
I believe you have a syntax error " removeDuplicates:(dataObject){ ..."
should be without the ":" >> " removeDuplicates(dataObject){ ... "
"
You can try this :
function removeDuplicates(arr){
var match={}, newArr=[];
for(var i in arr){ if(!match[arr[i].name]){ match[arr[i].name]=1; var newArr=i; } }
return newArr;
}
arr = removeDuplicates(arr);
You can use $.unique(), $.map(), $.grep()
var arr = [
{level:0,name:"greg"},
{level:0,name:"Math"},
{level:0,name:"greg"}
];
var res = $.map($.unique($.map(arr, el => el.name)), name =>
$.grep(arr, el => el.name === name)[0]);
jsfiddle https://jsfiddle.net/4tex8xhy/3
Or you can use such libraries as underscore or lodash (https://lodash.com/docs/4.16.2). Lodash example:
var arr = [
{level:0,name:"greg"},
{level:0,name:"Math"},
{level:0,name:"greg"}
];
var result = _.map(_.keyBy(arr,'name'));
//result will contain
//[
// {
// "level": 0,
// "name": "greg"
// },
// {
// "level": 0,
// "name": "Math"
// }
//]
Ofc. one thing to always consider in these tasks, what do you want exactly are you going to do: modify an existing array, or get a new one back. This example returns you a new array.