Compare 2 json file and delete object - javascript

I have 2 JSON files: A which is on a remote server, and B which is in local storage.
I'd like, on page load, for jQuery to compare both files and, if an object is in the B file, but not in A, for the object to be removed from local storage.
var fileA = '[{"ID":"1","foo":"bar"},{"ID":"3","foo":"bar"}]'; //Remote file
var fileB = '[{"ID":"2","foo":"bar"},{"ID":"3","foo":"bar"}]'; //localStorage
var jsonA = JSON.parse(fileA);
var jsonB = JSON.parse(fileB);
jsonA.forEach(function(allA) {
jsonB.forEach(function(allB) {
if (allA.ID != allB.ID) {
var i = jsonB.findIndex(mydata => mydata.ID === allA.ID);
if (i !== -1) {
jsonB.splice(i, 1);
if (jsonB.length === 0) {}
localStorage.setItem('panier', JSON.stringify(jsonB));
}
}
})
})
What I'm trying to do is delete ID:2 from local storage because it's not in A.

Check this code below:
Tips: Avoid using nested forEach loop to increase efficiency.
var fileA = '[{"ID":"1","foo":"bar"},{"ID":"3","foo":"bar"}]';//Remote file
var fileB = '[{"ID":"2","foo":"bar"},{"ID":"3","foo":"bar"}]'; //localStorage
var jsonA = JSON.parse(fileA);
var jsonB = JSON.parse(fileB);
// Temporary array to hold all id in file a
var arrA = [];
//Push all id in file A to arrA
jsonA.forEach(a => {
arrA.push(a.ID);
});
jsonB.forEach((b,index) => {
// check if arrA has b.ID
if (arrA.indexOf(b.ID) == -1){
jsonB.splice(index,1)
}
})
console.log(jsonB)
localStorage.setItem('panier', JSON.stringify(jsonB));

Try the following:
var fileA = '[{"ID":"1","foo":"bar"},{"ID":"3","foo":"bar"}]';//Remote file
var fileB = '[{"ID":"2","foo":"bar"},{"ID":"3","foo":"bar"}]'; //localStorage
var jsonA = JSON.parse(fileA);
var jsonB = JSON.parse(fileB);
jsonB = jsonB.filter((o) => jsonA.findIndex((obj)=> obj.ID === o.ID)!=-1 );
console.log(jsonB);

Related

Not getting the output for JSON.strigify()

Here I'm trying store the name of the id and the number of times it has been clicked.
It's stores as an object but when I tried JSON.Stringify() it returns a empty array like this
'[]'
if (localStorage.getItem('cart') == null) {
var cartArr = {};
} else {
cartArr = JSON.parse(localStorage.getItem('cart'));
}
const cartClass = document.querySelectorAll(".cart");
cartClass.forEach((ele) => {
ele.addEventListener('click', (e) => {
let cartId = (e.target.getAttribute('id'));
if (cartArr[cartId] == undefined) {
cartArr[cartId] = 1;
} else {
cartArr[cartId] += 1;
}
localStorage.setItem('cart', JSON.stringify(cartArr));
console.log(localStorage.getItem('cart'));
});
});
Your code should work. You never stored an array in that code. Perhaps you have another code that stored cart as an array?
I would delegate and give the system a tiny bit of time to react
const cartStr = localStorage.getItem('cart')
cartArr = cartStr ? JSON.parse(cartStr) : {}
const cartContainer = document.getElementById("cartContainer");
cartContainer.addEventListener('click', (e) => {
const tgt = e.target.closest(".cart");
if (tgt) {
let cartId = tgt.id;
cartArr[cartId] = cartArr[cartId] ? cartArr[cartId] : 0;
cartArr[cartId]++;
localStorage.setItem('cart', JSON.stringify(cartArr));
setTimeout(function() {
console.log(localStorage.getItem('cart'))
}, 10); // give the system time to react
}
});
I have checked your code, it works correctly. Your problem can be solved by cleaning your localStorage. It seems that at some point you have stored an empty array into your local storage. What happens is, JSON.stringify stores the contents of array, but ignores any custom properties you set on an array object:
// This will log "[]"
const arr = [];
arr.prop = "val"
console.log(JSON.stringify(arr));
// This will log {"prop": "val"}
const obj = {};
obj.prop = "val"
console.log(JSON.stringify(obj));

Javascript create nested Keys from Values under eachother & save to a new .json file

I have been racking my head to solve this.
Assuming we have the below CSV
const csv=[
"col1,col2,col3,col4,col5,col6",
"frequency,Weekly,haha,U45,A,WEEKLY",
"frequency,Every two weeks,def,hel,B,BI-WEEKLY",
"Time,Monthly,ghi,Tar,C,MONTHLY",
"Time,Every two months,oiu,60T,D,BI-MONTHLY",
"type,Quarterly,ppp,Q12,E,QUARTERLY",
"type,Half yearly,qwf,Y34,F,SEMI-ANNUALLY"]
what i am trying to do is create the nested json, which is not working in addition to that to get the below in a new json file, named with the value of col1.
meaning grouping all rows with a common col1 in a single file like below.
if col3, col 4 are the same & col5 & col6 are different the nest should be as below. drop col2.
{
"haha": {
"U45": {
"A": "Weekly"
"B": "Semi-annually"
}
}
}
what i have done so far is this.
const attrs = csv.splice(0,1);
function nested (obj, path, value) {
let lastKeyIndex=path.length-1;
lastKeyIndex.map(i => {
let key = path[i];
if (!(key in obj)) {
obj[key]={}
}
obj=obj[key]
})
obj[path[lastKeyIndex]]=value;
}
csv.map(line => {
let [col1,col2,col3,col4,col5,col6] = line.split(',')
let obj={}
nested (obj, [col3, col4, col5], col6)
return obj
})
your help is greatly appreciated.
You will have to use the node fs plugin to save the different files. I've marked the lines that you should uncomment in the node environment with // node only.
What I've done is loop through col3 - col6, check if the property exists in the parent object, if not create a new object, and then use that to check for the children. If you are on the last property, instead of creating a new object, use col6.
// const fs = require("fs"); // node only
let csv = [
"col1,col2,col3,col4,col5,col6",
"frequency,Weekly,haha,U45,A,WEEKLY",
"frequency,Every two weeks,def,hel,B,BI-WEEKLY",
"Time,Monthly,ghi,Tar,C,MONTHLY",
"Time,Every two months,oiu,60T,D,BI-MONTHLY",
"type,Quarterly,ppp,Q12,E,QUARTERLY",
"type,Half yearly,qwf,Y34,F,SEMI-ANNUALLY"
];
csv.splice(0, 1);
function addProperty(root, pathList) {
var lastValue = pathList.splice(pathList.length - 1, 1)[0];
pathList.forEach(function (path, index) {
var obj = root[path];
if (!obj) {
obj = (index === pathList.length - 1) ? lastValue : {};
root[path] = obj;
}
root = obj;
});
}
function jsonText(obj) {
return JSON.stringify(obj, (key, value) => value, 4);
}
var files = csv.reduce(function (result, line) {
var [fileName, , ...pathList] = line.split(",");
var fileInfo = result[fileName];
if (!fileInfo) {
fileInfo = {};
result[fileName] = fileInfo;
}
addProperty(fileInfo, pathList);
return result;
}, {});
console.log(jsonText(files));
// for (var path in files) fs.writeFileSync(path + ".json", jsonText(files[path])); // node only

create nested object from string JavaScript

I have a string like this:
let user = "req.user.role"
is there any way to convert this as nested objects for using in another value like this?
let converted_string = req.user.role
I know I can split the user with user.split(".")
my imagination :
let user = "req.user.role".split(".")
let converted_string = user[0].user[1].user[2]
I found the nearest answer related to my question : Create nested object from query string in Javascript
Try this
let user = "req.user.role";
let userObj = user.split('.').reduceRight((obj, next) => ({
[next]: obj
}), {});
console.log(userObj);
Or this, for old browsers
var user = "req.user.role";
var userArray = user.split('.'), userObj = {}, temp = userObj;
for (var i = 0; i < userArray.length; i++) {
temp = temp[userArray[i]] = {};
}
console.log(userObj);
The function getvalue() will return the nested property of a given global variable:
var user="req.user.role";
var req={user:{role:"admin"}};
function getvalue(str){
return str.split('.').reduce((r,c,i)=>i?r[c]:window[c], '');
}
console.log(getvalue(user));
I'll take my shot at this:
let user = "req.user.role"
const trav = (str, o) => {
const m = str.split('.')
let res = undefined
let i = 0
while (i < m.length) {
res = (res || o)[m[i]]
if (!res) break
i++
}
return res
}
const val = trav(user, {
req: {
user: {
role: "admin"
}
}
})
console.log(val)
this function will traversed the passed in object for the entire length of the provided string.split "." list returning either a value or undefined.
You can do it like this:
let userSplitted = "req.user.role".split('.');
let obj, o = obj = {};
userSplitted.forEach(key=>{o=o[key]={}});

Issues with JSON formatting for data object in Grafana

Data is not coming in with proper JSON formatting, so I'm having to loop through items in the array to fix the formatting, parsing the changed items and I cannot use the new object(s) when everything is finished because it is no longer in an array. The data is coming in as follows:
data [datapoints: [0..1..]
target: "up{cluster="bluehills_c3260_cluster",component="atr",datacenter="bluehills",hostname="ny-153-177"...}"]
Is there an easier way to convert this using a .map function or some other method to make things cleaner and get the desired result?
I've tried several methods including .replace, .map, and .push. I've also tried JSON.stringify, but nothing else seems to work except what I currently have.
onDataReceived(data) {
var i;
for (i = 0; i < data.length; i++) { // Loop through data array
var txt = data[i].target; // Create the variable to store the data target
var j;
for (j = 0; j <= txt.length; j++) { // Loop through the data target
var newObj = txt.slice(2,j); // Remove "up"
var filteredObj = newObj // Change over to JSON format...
.replace(/=/g,' : ')
.replace(/,/g,', ')
.replace(/{/g,'{ ')
.replace(/cluster/g,'"cluster"')
.replace(/component/g,'"component"')
.replace(/datacenter/g,'"datacenter"')
}
var dataObj = filteredObj.replace(/_"cluster"/gi,'_cluster');
var finalObj = JSON.parse(dataObj);
console.log("finalObj", dataObj);
}
}
What I want is a single array with the proper JSON format for the data (target) coming in.
How about this?
const myReg = /([\w\s]+)=\"([^"]*)\"/g
const str = `data [datapoints: [0..1..] target: "up{cluster="bluehills_c3260_cluster",component="atr",datacenter="bluehills",hostname="ny-153-177"...}"]`;
let matches = null;
const resultsJson = {};
while(matches = myReg.exec(str)){
resultsJson[matches[1]] = matches[2];
}
{ cluster: 'bluehills_c3260_cluster',
component: 'atr',
datacenter: 'bluehills',
hostname: 'ny-153-177' }
Not sure if this is how you want to have the data stored but that part would be pretty easy to customize.
onDataReceived(data){
this.createCosmo(data);
}
createCosmo(data) {
var arr = $.map(data,function(value){
return value.target;
});
var arr2 = $.map(arr,function(value){
var newObj = value.slice(2); // Remove "up"
var filteredObj = newObj // Change over to JSON format
.replace(/=/g,' : ')
.replace(/,/g,', ')
.replace(/{/g,'{ ')
.replace(/cluster/g,'"cluster"')
.replace(/component/g,'"component"')
.replace(/datacenter/g,'"datacenter"')
.replace(/hostname/g,'"hostname"')
.replace(/instance/g,'"instance"')
.replace(/job/g,'"job"')
.replace(/resilience_group/g,'"resilience_group"')
.replace(/_"cluster"/gi,'_cluster')
.replace(/-"cluster"/gi,'-cluster');
var finalObj = JSON.parse(filteredObj); // Parse the Object into JSON
return finalObj;
});
}

How can I capture a hash to Object in functional JavaScript?

I'm writing a piece of code in JavaScript for modern browser. I'm not using lodash or underscore as we want to keep the library as small as possible.
For example,
If the url comes like this. http://something.com/#hash=value
And the app is configured to capture key hash then the result would be this. Nothing fancy. I was just wondering if there's a better way or simple way to do this.
{
'hash': 'value'
}
The code
var config = Object.assign({}, {
capturedHashParams: ['hash']
});
var hashValue = '#hash=value1'.substr(1);
var capturedHashParams = {};
if (config.capturedHashParams && Array.isArray(config.capturedHashParams)) {
var splitedHash = hashValue.split('=');
if (splitedHash.length > 0) {
var key = splitedHash[0] || '';
var value = splitedHash[1] || '';
if (key && value) {
config.capturedHashParams.forEach(function(hp) {
if (hp.toLowerCase().indexOf(key.toLowerCase()) > -1) {
capturedHashParams[key] = value;
}
});
}
}
}
console.log(capturedHashParams);
https://jsfiddle.net/c92p0rfm/2/
i think you are watching for something like this:
var output = [];
var hashString = window.location.hash;
var hashArray = hash.split('&');
for(var index = 0; index < hashArray.length; index++){
var text = hashArray[index];
var tempArray= text.split('=');
var object = {
id: tempArray[0],
value: tempArray[1]
};
output[index] = object;
}
now output looks like this:
[
{
id: "hash",
value: "value"
}
]
Your question is somewhat ambiguous. It appears that you want to extract key/value pairs from an url hash and return as a JavaScript object. I am bit uncertain about whether you want to extract all key/value pairs or only those provided in a config object. I am also a bit uncertain as to whether you want a solution within a strict functional programming paradigm, or just a plain solution with a small code footprint. I will assume the latter.
A straightforward approach to capture all key/value pairs:
var url = 'http://something.com/#hash=value&anotherHash=value';
//extract key=value pairs from url
var params = url.split('#').pop().split('&');
//assign to data object
for(var data = {}, i = 0, temp; i < params.length; i++){
// extract array [key, value]
temp = params[i].split('=');
// assign to data object
data[temp[0]] = temp[1];
}
console.log(data);
A more compact solution to do the same with .reduce():
var url = 'http://something.com/#hash=value&anotherHash=value';
var data = url
.split('#')
.pop()
.split('&')
.reduce(function(obj, keyval){
keyval = keyval.split('=');
obj[keyval[0]] = keyval[1];
return obj;
}, {});
console.log(data)
If you want to configure which keys to extract:
var url = 'http://something.com/#hash=value&anotherHash=value&notThisHash=value';
//config object
var keysToCapture = [
'hash',
'anotherHash'
];
var data = url
.split('#')
.pop()
.split('&')
.reduce(function(obj, keyval){
keyval = keyval.split('=');
if(keysToCapture.indexOf(keyval[0]) > -1){
obj[keyval[0]] = keyval[1];
}
return obj;
}, {});
console.log(data)
Which you could capture in a reusable function like this:
function extractParamsObject(url, keysToCapture){
return url
.split('#')
.pop() //hash/fragment: everything after the last #
.split('&')
.reduce(function(obj, keyval){
keyval = keyval.split('=');
if(keysToCapture.indexOf(keyval[0]) > -1){
obj[keyval[0]] = keyval[1];
}
return obj;
}, {});
}
console.log(extractParamsObject(
'http://something.com/#hash=value&anotherHash=value&notThisHash=value',
['hash', 'anotherHash']
));

Categories