create JSON object from another JSON object - javascript

I don't know if the title is the right one for what I want to do.
I have the following array of objects
array([0]: {category: "10",
question: "101"},
[1]: {category: "10",
question: "102"},
[2]: {category: "20",
question: "201"}
);
And I want to group all the elements into something like this:
array([0]: {category: "10", {question: "101",
question: "102"}},
category: "20", {question: "201"}});
I don't know if this is possible or if there's another better way to solve this problem (maybe with a two-dimensional array?) but any help would be very appreciated.
Thanks!
Sorry for the lack of information, here is how I create my array of objects:
var arr_sections = [];
var arr_questions = [];
var jsonObj = [];
$('.ui-sortable-nostyle').each(function(){
arr_sections.push($(this).attr("sec_id"));
});
// create json object with pairs category - question
$(".sortable2").each(function(i){
$(this).children().each(function(j){
var cat = arr_sections[i];
jsonObj.push({
category: arr_sections[i],
question: $(this).attr("ques_id")
});
});
});
And got an array of objects with the following structure:
[Object, Object, Object, Object, Object]
0: Object
category: "1052"
question: "3701"
__proto__: Object
1: Object
category: "1053"
question: "3702"
__proto__: Object
2: Object
category: "483"
question: "1550"
__proto__: Object
3: Object
category: "483"
question: "1548"
__proto__: Object
4: Object
category: "483"
question: "1549"
__proto__: Object
length: 5
Tried to create my new array:
for(var i = 0; i < jsonObj.length; i++){
temp[jsonObj[i].category] = jsonObj[i].question;
}
But I don't get all values:
[483: "1549", 1052: "3701", 1053: "3702"]

You have:
var arr = [
{category: "10", question: "101"},
{category: "10", question: "102"},
{category: "20", question: "201"}
];
You want (i suppose):
var arrRequired = [
{category: "10", question : ["101", "102"] },
{category: "20", question : ["201"] }
];
I will give you:
var obj = {
"10" : ["101", "102"],
"20" : ["201"]
};
To convert what you have to what i will give you, you can do:
var result = {};
arr.forEach(function(item) {
if (!result[item.category])
result[item.category] = [item.question];
else
result[item.category].push(item.question);
});
To get to what you want from what i gave you, you can do:
var arrRequired = [];
for (var category in result){
arrRequired.push({ 'category' : category, 'question' : result[category] });
}
If that is not what you want, then perhaps you should explain it better, using valid syntax.

Here is the answer to what you asked:
var object1 = JSON.parse(jsonString1);
// Do something to object1 here.
var jsonString2 = JSON.stringify(object1);

Related

filtering an array of object based on string array

my problem might not be as challenging as some other similar questions but they were a little to much for me.
I have an array of objects that I need to filter by name against a string array of names, if the names match I want to remove the object with the name that matches
so like the following:
nameObjects = [{name: 'name3', value: 'some val'},{name: 'name1', value:'some other val'}]
names = ['name1','name2','name3']
I've tried the following just using for loops but I'm sure that there is a quicker (and correct lol) filter method that works
for(i=0; i < this.names.length; i++){
for(j=0; j < this.nameObjects.length; j++){
if(this.names[i] === this.nameObjects[j].name){
this.files.splice(i,this.nameObjects[j])
}
}
}
also sorry for the poor logic ^
You should not mutate the array while you are looping over it.
You can simply use Array.prototype.filter with Array.prototype.includes to get the desired result
const nameObjects = [{name: 'name3', value: 'some val'},{name: 'name1', value:'some other val'}];
const names = ['name2','name3'];
const res = nameObjects.filter(obj => !names.includes(obj.name));
console.log(res);
const nameObjects = [
{ name: "name3", value: "some val" },
{ name: "name1", value: "some other val" },
];
const names = ["name1", "name2"];
const result = nameObjects.filter(obj => !names.includes(obj.name));
console.log(result);

How can I get data iterate Json?

I need get data the my Json but I can't use 'key' because the 'key' is different each day.
I tried :
template: function(params) {
const objects = JSON.parse(JSON.stringify(params.data.masterdetail));
for (const obj of objects) {
const keys = Object.keys(obj);
const cont = 0;
keys.forEach(key => {
const valor = obj[key];
console.log('value ', valor[0]);
});
}
I first tried with 0 and then use cont, but with 0 console.log (value is undefined)....
If I use console.log ('value' , valor['name']) IT'S OK ! but I can't use keys and if I use valor[0] is undefined...........
Example Json
{
"headers": [
"headerName": "asdasd",
], //end headers
"datas": [
"idaam": "11",
"idorigen": "11",
"masterdetail": [{
"child1": {
"name": "I AM",
"age": "1"
},
"child2": {
"name": "YOU ARE",
"age": "2"
},
"child3": {
"name": "HE IS",
"age": "3"
},
}] //end masterdetail
]//end datas
}//end JSON
Edit :
I can't use 'keys' because today I receive "name", "typeval" etc. and tomorrow I can get 'surname','id' etc.
If you see in my first img you can see "4" bits of data.
1º obj[key]{
name = "adopt",
typeval= "",
etc
}
2º obj[key]{
"link" = "enlace",
"map" = "map"
etc
}
If I use this code : I get "name" OKEY but
I HAVE PROHIBITED use of value['name'] or value[typeval] because this Json always is dynamic.
var objects = params.data.masterdetail[0];
const keys = Object.keys(objects);
let value;
keys.forEach(key => {
value = objects[key];
console.log(value['name']);
console.log(value['typeval']);
});
I need for example :
var objects = params.data.masterdetail[0];
const keys = Object.keys(objects);
cont = 0 ;
keys.forEach(key => {
value = objects[key];
console.log(value[0]);
});
but value[0] is undefined and then when I arrive 2ºobj[key] link is index 0 but cont maybe is .... 4...
Sorry for my English...
To simply print the objects within the first entry in the masterdetail array, you can do the following:
var objects = params.datas.masterdetail[0];
const keys = Object.keys(objects);
keys.forEach(key => {
console.log('value ', objects[key]);
});
Based on a (suitably corrected - see my comments above) version of the JSON above, this would produce console output as follows:
value {name: "I AM", age: "1"}
value {name: "YOU ARE", age: "2"}
value {name: "HE IS", age: "3"}
Unfortunately it's not 100% clear from the question if this is the output you were looking for, but that's my best guess based on the code.
Your main mistakes were that
1) masterdetail is an array, and all the data is within the first element of that array, so to get the objects within it you need to select that element first. If the array can have multiple elements in real life then you'd need an outer loop around the code above to iterate through it.
2) If you're looping through the keys of an object, you don't need to also iterate through the properties a different way. You seemed to have two loops designed to do the same thing.

Converting array of objects and nested array to JSON

I have an API endpoint that expects the following json string (this is an example).
{
"userid": "1234",
"bookshelf": "3",
"bookcount": "6",
"books":[
{"bookid": "1"},
{"bookid": "2"},
{"bookid": "3"},
{"bookid": "6"}
]}
The api accesses each in the following manner:
$userid = $data['userid'];
$bookshelf = $data['bookshelf'];
etc...
I can also loop through the books and get each bookid with:
$data['books'][$i]['bookid']
When I send the above json string via a tool like postman it works fine. I'm having trouble manufacturing this same json string on the javascript side. This is how I populate the data on the front end of my site.
var data = new Array();
data.push({ "userid": "1234" });
data.push({ "bookshelf": "3" });
data.push({ "bookcount": "6" });
data.push({ "books": selectedbooks }); // This is an array of bookid objects
The problem is whether I json.stringify it and send to the webserver and over to the api or have the webserver json_encode, I end up with numeric indexes that can only be accessed like $data[0]['userid']; once it's decoded by the api, which differs from how the api is working. This would require the json string to be assembled in an exact sequence if the api supported it.
How do I go about getting this data in the required format?
The numeric indexes are coming because you're preparing the data as an array, not an object. Arrays in JavaScript are indexed, not associative. Try:
var data = {
userid: 1234,
bookshelf: 3,
bookcount: 6,
books: selectedbooks
};
You need to create an object, not an array.
var data = {};
data["userid"] = "1234";
data["bookshelf"] = "3";
data["bookcount"] = "6";
data["books"] = selectedbooks; // This is an array of bookid objects
Your data is not supposed to be an array, it's an object. The only array is in the books property.
var data = {}
data.userid = "1234";
data.bookshelf = "3";
data.bookcount = "6";
data.books = selectedbooks;
or more succintly:
var data = {
userid: "1234",
bookshelf: "3",
bookcount: 6,
books: selectedbooks
};
You can easily transform your array into the expected object :
var arr = [
{"userid": "1234"},
{"bookshelf": "3"},
{"bookcount": "6"},
{
"books":[
{"bookid": "1"},
{"bookid": "2"},
{"bookid": "3"},
{"bookid": "6"}
]}
];
var obj = {} ;
arr.forEach(item => {
var key = Object.keys(item)[0];
obj[key] = item[key];
});
console.log(obj);
//{ userid: '1234',
// bookshelf: '3',
// bookcount: '6',
// books:
// [ { bookid: '1' },
// { bookid: '2' },
// { bookid: '3' },
// { bookid: '6' } ] }

Old JSON value Changed

I have two JSON objects columnsData and columns when assigning columnsData value to columns both values are changed.
var columnsData = [
{id: "id"},
{id: "root_task_assignee"},
{id: "root_task_id"},
{id: "root_task_status"},
{id: "root_task_tracker"},
{id: "rt_category"},
{id: "rt_priority"},
{id: "rt_subject"},
]
var columns = [];
using the below function I assigned the columnsData value to columns object, and also added some additional fields
for(i = 0;i < columnsData.length; i++){
columns[i] = columnsData[i];
columns[i]["name"] = columnsData[i]["name"] || columnsData[i]["id"];
columns[i]["type"] = columnsData[i]["id"]["type"] || "string";
}
but after assigning both have the same values. How the old JSON columnsData value was changed? is there any other way to assign values
columns[i] = columnsData[i] does not copy the data, it makes an additional reference to the same data.
For example, say you give Mr. Random Jones a nickname, "Cozy". If you give Cozy an envelope to hold, are you surprised if Mr. Jones is now holding an envelope too?
Same thing here. If you change columns[i], you are also changing columnsData[i], since they are the same object.
You would have to clone it if you wanted to have them be different. In this case, you just have to make a new object with id:
columns[i] = { id: columnsData[i].id };
In general, you would do well to find a nice clone function.
If it is required to keep original array pure (unchanged) we should use map method of array.
var columnsData = [
{id: "id"},
{id: "root_task_assignee"},
{id: "root_task_id"},
{id: "root_task_status"},
{id: "root_task_tracker"},
{id: "rt_category"},
{id: "rt_priority"},
{id: "rt_subject"},
]
var columns = columnsData.map(function(obj){
var rObj = {};
rObj[obj.key] = obj.value;
rObj["name"] = obj.value;
.....
return rObj;
});
Logic can be added in map method to create new array as required. Hope it helps.
columns[i] = columnsData[i] will not copy content from one object to another but it will an reference of the columnsData[i]. As they are refereeing to same object, change in property of one object will affect the primary object which is being refereed.
Try this:
var columnsData = [{
id: "id"
}, {
id: "root_task_assignee"
}, {
id: "root_task_id"
}, {
id: "root_task_status"
}, {
id: "root_task_tracker"
}, {
id: "rt_category"
}, {
id: "rt_priority"
}, {
id: "rt_subject"
}, ]
var columns = [];
for (i = 0; i < columnsData.length; i++) {
var obj = {};
obj["name"] = columnsData[i]["name"] || columnsData[i]["id"];
obj["type"] = columnsData[i]["id"]["type"] || "string";
columns.push(obj)
}
alert(JSON.stringify(columns));
alert(JSON.stringify(columnsData));

How to append this JavaScript array object to another JavaScript array object?

I have this Javascript json array object;
var dataJson=[ [{v:1},{v:90}],[{"v":2},{"v":"33.7000"}] ];
I want to append this array object dataJson to another object such that it looks like this;
var chartObject = {"cols": [
{id: "t", label: "t_label", type: "number"},
{id: "s", label: "s_label", type: "number"}
], "rows": [
{c:
[{v:1},{v:90}] //dataJson[0]
},
{c:
[{"v":2},{"v":"33.7000"}] ////dataJson[1]
}
]};
How do I use a for loop to insert dataJson elements into chartObject? I am sorry I am quite new to javascript and can't even produce some starting code. Thank you very much for any help.
Try this:
...
], "rows": dataJson.map(function(row) {return {c:row};})
};
Javascript objects are pretty amazing things. Just define a new field in chartObject as an array, and then push whatever json data you want into it. It looks you want rows to be an array of objects which have an identifier for each json object, but unless you explicitly want to name each dataJson with a string, then just use an indexed array:
chartObject["rows"] = [];
for(var i = 0; i < dataJson.length; i++) {
chartObject["rows"].push(dataJson[0]);
}
Now you can access each piece of data with:
chartObject["rows"][index]
And each field in the data with:
chartObject["rows"][index]["v"]
Using the simple and clean way:
var chartObject = {"cols": [
{id: "t", label: "t_label", type: "number"},
{id: "s", label: "s_label", type: "number"}
]};
var dataJson=[ [{v:1},{v:90}],[{"v":2},{"v":"33.7000"}] ];
chartObject["rows"] = []; // start with empty array
// iterate over first dataJson array
for(var i = 0, len = dataJson[0].length; i < len; i++){
// push in array `c` mapped to the i-th element of dataJson[0]
chartObject["rows"].push({c : dataJson[0][i]["v"]});
}
console.log(chartObject);
DEMO
Ignore those [object Object] in DEMO
Sample Output:
{
cols: [{
id: "t",
label: "t_label",
type: "number"
}, {
id: "s",
label: "s_label",
type: "number"
}],
rows: [{
c: 1
}, {
c: 90
}]
}

Categories

Resources