Add subelement to JSON array - arrays

I have the following code where I design the format of a JSON-array dynamically from variables ==>
var Title = '"text_title"'
var Topic2 = '"text_topic2"'
var jsonData = [ ];
createWantedJSON("title", data[i].topic, jsonData)
function createWantedJSON(title, Topic2, arr) {
arr.push({
"Topic": title,
[Topic2] : {
"Topic3": [{
"Subitem1": "Text1",
"Subitem2": "Text2",
"Subitem3": "Text3"
}]
}
}
This goes fine for the key and value which are not nested. But I don't know how to make it dynamic for the content of Topic3. I tried making a variable with the following content =>
'"Subitem1": "Text1", "Subitem2": "Text2", "Subitem3": "Text3"' but then of course it sees the content as one string and not as elements of the nested Topic3 array. I guess this isn't that hard but I can't seem to fix it.

Related

Resolving simple references in a spreadsheet structure. Is this a linked list problem?

I have this job test task where I am need some help.
I have to somehow dynamically access the value in the data stucture below, through references. To this point I used loops and indexOf() in an ordered alphabet and numbers. indexOf("B") in alphabet is [[ 1 ]], indexOf(1) is [0] for the two dimensional array.
Here "B1" is referencing "C1", "C1" references "D1" .. to "H1" and when "H1" points to the text "Last", all of the formulas should turn into the same value - the text "Last".
But how? Been breaking my head for a couple of hours and remembered linked lists, but so far have no clue how to implement them. How can I achieve this?
{
data: [
[
{ reference: "B1" },
{ reference: "C1" },
{ reference: "D1" },
{ reference: "E1" },
{ reference: "F1" },
{ reference: "G1" },
{ reference: "H1" },
{ text: "Last" },
]
],
id: "job-20"
}
It looks like you need to work with a spreadsheet type of data structure, and need to recalculate cells based on the formulas they have.
You can use recursion for that.
The base case happens when you arrive at a cell that has no reference. In that case the text of that cell can be returned to the caller. And that caller will assign that text to the cell it was looking at, and also returns that to their caller...etc.
function get(reference) { // return the cell object at the given reference
return data[reference.slice(1)-1][reference.charCodeAt() - "A".charCodeAt()];
}
function resolve(cell, visited=new Set) {
// Have we found a cell with just text? Then return that to caller
if (!("reference" in cell)) return cell.text;
// Did we already meet this cell before? Then we are running in circles!
if (visited.has(cell)) return "Circular Reference!";
// Make a recursive call to know what the text should be
cell.text = resolve(get(cell.reference), visited.add(cell));
delete cell.reference;
return cell.text; // Return this value also to the caller
}
function calculate(data) {
// Get to each cell object...
for (let row of data) {
for (let cell of row) {
resolve(cell); // And update its text property by following references
}
}
}
let data = [
[
{reference: "B1"}, {reference: "C1"}, {reference: "D1"}, {reference: "E1"},
{reference: "F1"}, {reference: "G1"}, {reference: "H1"}, {text: "Last"},
]
];
calculate(data);
console.log(data);
It should be noted that in a real spreadsheet the references (formulas) are not deleted during such a recalculation. The cell will have both the text and the reference, so that when a cell's text is updated, all other dependent cells get their own text updated accordingly again.

Remove duplicate content from array

"name": [
{
"name": "test1"
},
{
"name": "test2"
},
{
"name": "test3"
},
{
"name": "test1"
},
]
I have the above created by nodejs. During array push, I would like to remove duplicated arrays from the list or only push the name array if the individual array does not exist.
I have tried below codes but it changes the array.
var new = [];
for (var i =0;i<name.length;i++){
new['name'] = name[i].name;
}
The easiest way is probably with Array.prototype.reduce. Something along these lines, given your data structure:
obj.name = Object.values(obj.name.reduce((accumulator, current) => {
if (!accumulator[current.name]) {
accumulator[current.name] = current
}
return accumulator
}, {}));
The reduce creates an object that has keys off the item name, which makes sure that you only have unique names. Then I use Object.values() to turn it back into a regular array of objects like in your data sample.
the solution can be using temp Set;
const tmpSet = new Set();
someObj.name.filter((o)=>{
const has = tmpSet.has(o.name);
tmp.add(o.name);
return has;
});
the filter function iterating over someObj.name field and filter it in place if you return "true". So you check if it exists in a tmp Set & add current value to Set to keep track of duplicates.
PS: new is a reserved word in js;
This should do it
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
let unique = [...new Set(names)];
console.log(unique); // 'John', 'Paul', 'George', 'Ringo'
https://wsvincent.com/javascript-remove-duplicates-array/

cookie in React JS (save/load)

I am new to using cookies in React JS and I have a question regarding my code below.
console.log(this.state.datasets);
cookie.save('datasets', this.state.datasets, { path: '/' , 'maxAge': 100000});
var myArray = cookie.load('datasets')
console.log(myArray);
this.state.datasets is an array full of elements and went I initially print the array to the console, I am able to see the data.
However when I try printing out myArray I get an empty array. Any idea what could be going wrong?
You can save only strings as cookies. To save an array you'll have to somehow convert it into a string. If you have an array of objects you can store it by converting it into string by JSON.stringify.
For example
let colors = [
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
}]
let x = JSON.stringify(colors)
The value x will be a string which you can save to cookies.
And to retrieve it you can convert it back to an array of objects by using JSON.parse.
Something like
var myArray = cookie.load('datasets')
let obj = JSON.parse(myArray)
obj will be the original object

How dynamically transform my "Object" to List in ng-model at view

I'm trying to transform my object to list dynamically, so I'm building at view instead of declaring at controller.
I don't want to declare like this: custom_fields.title_field.type_text_field = [] because the title_field is built dynamic, it could be any kind of text like full_name
My json as is:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":{
"name":"John",
"first_name":"Wick"
},
"type_boolean_field":{
"is_badass": true,
"is_good_movie": true
},
"type_select_field": {
"this_select": 1,
"i_got_this": "nope i didnt got this"
}
},
And to be:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":[{
"name":"John",
"first_name":"Wick"
}],
"type_boolean_field":[{
"is_badass": true,
"is_good_movie": true
}],
"type_select_field": [{
"this_select": 1,
"i_got_this": "nope i didnt got this"
}]
},
the object I'm trying to transform into array is type_text_field which can be dynamic too, like type_date_field or type_select_field and so on.
My ng-model is like this:
ng-model="objectApp.application.applicant.custom_fields[layout.dynamic_title][input.type][input.variable]"
the [input.type] is that I'm trying to transform into array, how can I achieve this? I tried to use $index, but got strange results.
We can do it by 2 solutions:
There is a question about your task:
? how you want handle if we have more than one type_text_field in title_dynamic_generate_field? because you want to convert it to "type_text_field":[{},...]
however my answers about the question are:
If we know what's the dynamic params which we want to send theme as json, i mean if we know what is the key of title_dynamic_generate_field or type_text_field, we do as this sample:
var data = {
"custom_fields": {
dynamicParamIs1: 'title_dynamic_generate_field',
dynamicParamIs2: 'type_text_field',
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var paramHelper1 = json.custom_fields[json.custom_fields.dynamicParamIs1];
var paramHelper2 = json.custom_fields.dynamicParamIs2;
var solutionA = function (object, as) {
var array = [];
for (var key in object) {
var newObject = object[key];
array.push(newObject);
}
object[as] = array;
}
solutionA(paramHelper1, paramHelper2);
We changed a model of our json which can help us to detect (find) the keys
If we don't know what is the dynamic params are, we do as this:
var data = {
"custom_fields": {
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var solutionB = function (json) {
var array = [];
for (var key in json) {
var j1 = json[key];
for (var key2 in j1) {
var j2 = j1[key2];
for (var key3 in j2) {
var fullObject = j2[key3];
array.push(fullObject);
j2[key3] = array;
}
}
}
}
solutionB(data);
This sample is manual which we use nested for to detect the keys name

Add data to array within array in MongoDB

So heres my mongodb document:
{
"_id" : "",
"lists" : [
{
"name" : "list 1",
"items" : []
},
{
"name" : "list 2",
"items" : []
}
]
}
How would I go about adding an object inside "items"?
This is the code I have so far, but it doesn't work:
xxx.update(_id, {$push: { "lists.$.items": item}});
Note that I have access to the index (variable called 'index'), so its possible to insert an item at index, 0, 1, 2..., etc.
I tried this before, but it won't work:
xxx.update({_id, "lists": index}, {$push: { "lists.$.items": item}});
I also looked at other similar questions and couldn't find anything. Most of them have some sort of id field in their arrays, but I don't.
What about
xxx.update({_id}, {$push: { "lists.index.items": item}});
Of course this would fail, what I mean is replace index with real index values
xxx.update({_id}, {$push: { "lists.2.items": item}});
You can manipulate the update json based on the index maybe as below.
var update = '{$push: { "lists.'+index+'.items": '+item+'}}';
var updateObj = JSON.parse(update);
xxx.update({_id}, updateObj);
Not sure if it will work as it is or it would need further tweaking, but you get the idea.

Resources