I currently have an item in local storage which looks like this
"cars":[
{
"Id":7,
"Name":"Audi",
},
{
"Id":8,
"Name":"Ford",
}
I want to retrieve all of the Id's only and store them in a string.
At the minute I am pulling the data like this:
var cars = "";
cars= localStorage.getItem('cars');
var carArr= new Array();
carArr.push(cars);
How can I just obtain the Id's
If i understand your question correctly, you have to use Array.map to transform your array in combination with JSON.parse and JSON.stringify to read/write from the storage.
Here is an example using a "mocked" localStorage:
// use a mock storage because snippet doesn't allow localStorage usage.
var mockStorage = {};
// setup initial storage
try {
mockStorage.cars = JSON.stringify([
{
Id:7,
Name:"Audi",
},
{
Id:8,
Name:"Ford",
}
]);
} catch(e) {}
console.log('inital local storage:\n', mockStorage);
// example
var cars = [];
// parse JSON string value from storage to javascript object.
try {
cars = JSON.parse(mockStorage.cars)
} catch(e) {}
console.log('cars:\n', cars);
// transform array of cars to array of car ids
var ids = cars.map(car => car.Id)
console.log('car ids:\n', ids);
// transform array to JSON string
try {
mockStorage.cars = JSON.stringify(ids);
} catch(e) {}
console.log('local storage:\n', mockStorage);
localStorage only supports strings. So, you have to use JSON.parse to get the cars array from string and then use array#map to get all the ids.
var carsString = localStorage.getItem('cars');
var cars = JSON.parse(carsString);
var ids = cars.map( car => car.Id);
console.log(ids);
Use this,
//you get this from localStorage after you parse it
//JSON.parse(localStorage.cars);
var cars = [
{
"Id":7,
"Name":"Audi",
},
{
"Id":8,
"Name":"Ford",
}];
var res = [];
cars.forEach(function(val){
res.push(val.Id);
});
console.log(res);
Related
I want to find strings that has data from the strings from the array 2 in the array1 and save result as separate uniq array.
As can you see I search for not exact values. From the array1 values I know only part of the information, and I want to find the complete strings, with that information, in array1. And at the end I want to save what I found. So, I don't have a problem with finding here, but a problem with saving in the valid single JSON.
Array examples:
Array #1:
{
"overflow": [
"id:address:name:location:email",
...
"id2:address2:name2:location2:email2"
]
}
Array #2:
[
"location:email",
...
"location2:email2"
]
Code:
resultArr: function() {
var arr1 = '/var/log/1.json';
var arr2 = '/var/log/2.json';
var arrResult = '/var/log/result.json';
var arr2Obj = JSON.parse(fs.readFileSync(arr2, 'utf-8'));
for (var i = 0; i < arr2Obj.length; i++) {
var arr1Obj = JSON.parse(fs.readFileSync(arr1, 'utf-8'));
arr1Obj.overflow = arr1Obj.overflow.filter(function(e) {
return e.includes(arr2Obj[i])
});
fs.appendFile(arrResult, JSON.stringify(arr1Obj, null, 2), 'utf-8');
}
}
My result:
[{
"overflow": [
"id:address:name:location:email"
]
}{
"overflow": [
"id54:address54:name54:location54:email56"
]
}{
"overflow": [
"id2:address2:name2:location2:email2",
"id6:address6:name6:location2:email2"
]
}
What I really want:
{
"overflow": [
"id:address:name:location:email",
"id54:address54:name54:location54:email56",
"id6:address6:name6:location2:email2",
"id2:address2:name2:location2:email2"
]
}
Instead of reading the file again and again, and appending to the result repeatedly, just do both actions only once. All the rest should happen in memory.
You will also get better results (no risk for duplicates in result) when you swap the loops: put the filter action as the outer loop. For the inner loop you can use some, since one match is enough for the entry to be included:
resultArr: function() {
var arr1 = '/var/log/1.json',
arr2 = '/var/log/2.json',
arrResult = '/var/log/result.json',
arr2Obj = JSON.parse(fs.readFileSync(arr2, 'utf-8')),
arr1Obj = JSON.parse(fs.readFileSync(arr1, 'utf-8'));
arr1Obj.overflow = arr1Obj.overflow.filter(function(e) {
return arr2Obj.some(function (f) {
return e.includes(f)
});
});
fs.writeFileSync(arrResult, JSON.stringify(arr1Obj, null, 2), 'utf-8');
}
At each iteration, you're creating a new object and appening it to a file.
JSON is not a good format to append to.
You're replacing the array instead of adding fields to it.
You can do it that way, it should work :
resultArr: () => {
let arr1 = '/var/log/1.json';
let arr2 = '/var/log/2.json';
let arrResult = '/var/log/result.json';
let arr2Obj = JSON.parse(fs.readFileSync(arr2, 'utf-8'));
let arr1Obj = JSON.parse(fs.readFileSync(arr1, 'utf-8')); // reading only one time
arr1Obj.overflow = arr2Obj.map(value => {
return arr1Obj.overflow.filter(e => return e.includes(value))
});
fs.writeFileSync(arrResult, JSON.stringify(arr1Obj, null, 2), 'utf-8'); //Writing only one time
}
Array.map() executes the closure for each field in your array and group all the values returned by the closure in another array.
I also replaced some keywords to make your code more ES6 compliant. I you really want to append, you should use CSV and not JSON.
This is the data displaying in console.log.
{"data":
[
{
"CloserName":null,
"agent_id":"10807",
"AgentName":"TEST",
"SurveyDate":"02/02/2018 02:18:46 AM",
"SurveyName":"Ruth ",
"state":"West Bengal",
"phone":"9836969715",
"status":"Approved",
"verification_progress":"Pending",
"survey_id":"1",
"rejection_remarks":"aa",
"tl_remarks":"Pending"
}
],
"count":1
}
Can anyone help me display a single value (i.e survey_id)? I just want to fetch that survey_id
Here's an example:
var json = {
"data":[
{
"CloserName":null,
"agent_id":"10807",
"AgentName":"TEST",
"SurveyDate":"02/02/2018 02:18:46 AM",
"SurveyName":"Ruth ",
"state":"West Bengal",
"phone":"9836969715",
"status":"Approved",
"verification_progress":"Pending",
"survey_id":"1",
"rejection_remarks":"aa",
"tl_remarks":"Pending"
}
],
"count":1
}
// get first id
var id = json.data[0].survey_id
console.log(id)
// get all ids
var ids = json.data.map(x => x.survey_id)
console.log(ids)
If the JSON is stringified, call JSON.parse(jsonStr) first.
You have to parse the JSON-String into an object. After that you can access the data with default object-identifiers.
const object = JSON.parse('{"data":[{"CloserName":null,"agent_id":"10807","AgentName":"TEST","SurveyDate":"02/02/2018 02:18:46 AM","SurveyName":"Ruth ","state":"West Bengal","phone":"9836969715","status":"Approved","verification_progress":"Pending","survey_id":"1","rejection_remarks":"aa","tl_remarks":"Pending"}],"count":1}');
console.log(object.data[0].survey_id)
If your JSON data has been stringified (your sample JSON is a valid JSON object, not a string) you would first need to parse it, and then get the IDs (assuming you will have more than one item inside the data array) and log them out. There's a few different ways of achieving this:
const stringified = '{"data":[{"CloserName":null,"agent_id":"10807","AgentName":"TEST","SurveyDate":"02/02/2018 02:18:46 AM","SurveyName":"Ruth ","state":"West Bengal","phone":"9836969715","status":"Approved","verification_progress":"Pending","survey_id":"1","rejection_remarks":"aa","tl_remarks":"Pending"}],"count":1}';
let parsed = JSON.parse(stringified);
parsed = parsed.data.map(item => item.survey_id);
console.log(parsed);
You can also just loop over the items in the array and log them one by one using a for loop:
const stringified = '{"data":[{"CloserName":null,"agent_id":"10807","AgentName":"TEST","SurveyDate":"02/02/2018 02:18:46 AM","SurveyName":"Ruth ","state":"West Bengal","phone":"9836969715","status":"Approved","verification_progress":"Pending","survey_id":"1","rejection_remarks":"aa","tl_remarks":"Pending"}],"count":1}';
let parsed = JSON.parse(stringified);
for (let i = 0; i < parsed.data.length; i++) {
console.log(parsed.data[i].survey_id);
}
Or using a for-of:
const stringified = '{"data":[{"CloserName":null,"agent_id":"10807","AgentName":"TEST","SurveyDate":"02/02/2018 02:18:46 AM","SurveyName":"Ruth ","state":"West Bengal","phone":"9836969715","status":"Approved","verification_progress":"Pending","survey_id":"1","rejection_remarks":"aa","tl_remarks":"Pending"}],"count":1}';
let parsed = JSON.parse(stringified);
for (const item of parsed.data) {
console.log(item.survey_id);
}
According to your current object structure
Your object
var obj = {"data":[{"CloserName":null,"agent_id":"10807","AgentName":"TEST","SurveyDate":"02/02/2018 02:18:46 AM","SurveyName":"Ruth ","state":"West Bengal","phone":"9836969715","status":"Approved","verification_progress":"Pending","survey_id":"1","rejection_remarks":"aa","tl_remarks":"Pending"}],"count":1};
Fetching survey_id
obj.data[0].survey_id
Im trying to create a structure with Javascript as follows:
var users = {
user.id: {
session.id1: session.id1,
session.id2: session.id2,
session.id3: session.id3
},
user.id2: {
session.id1: session.id1,
session.id2: session.id2,
session.id3: session.id3
},
};
What i need: add new sessions and remove them, removing okay, but how should i define object and how can i push new sessions to user obejct? That's why key is equal to value.
If you want to use session.id1 instead of something like sessionId1 :
Assign value:
users['user.id'].['session.id1'] = value;
Create object:
var users = {
'user.id': {
'session.id1': session.id1,
'session.id2': session.id2,
'session.id3': session.id3
},
'user.id2': {
'session.id1': session.id1,
'session.id2': session.id2,
'session.id3': session.id3
},
};
But I don't recommend it. If you are the only one who is gonna work with this code, it's ok.
You can first create an empty object and fill it as and when the data comes like
users[user.id] = {};
For an example:
var users = {};
var user = {id : 1}; //Data received(Just an example)
users[user.id] = {};
var session = {id1 : 1.1}; //Data received
users[user.id][session.id1] = session.id1;
console.log(JSON.stringify(users));
How about refactoring the user object to store sessions as an array and push, pop and slice them as required.
var users = [
{
id:'userid',
sessions: [
{
id: 'sessionid',
sessiondata: something
},
{
id: 'sessionid',
sessiondata: something
}
]
}];
This way to can just use normal array operators on the session array for each user.
data = [{'name':'John'},
{'name':'Smith'},
{'name':'James'}]
how to format the above array into this
var name = {
"user": {
"name" : [{'name':'John'},
{'name':'Smith'},
{'name':'James'}]
}
}
I tried var name['name'] = data and don't know how to wrap the result. I want to wrap the result with 'user' as it assoc.
You can't assign properties as you create the object. Either first create the object and then set the property:
var name = {};
name.user = { name : data };
or create the entire object at once:
var name = { user: { name: data } };
var data = [{'name':'John'},
{'name':'Smith'},
{'name':'James'}]
var name = {
"user": {
"name" : data
}
}
I want the following structure:
var data={"users":[
{
"firstName":"Ray",
"lastName":"Villalobos",
"joined":2012
},
{
"firstName":"John",
"lastName":"Jones",
"joined":2010
}
]}
I want to be able to programatically add entries to it.
Here is what I tried:
var data = [];
data.push({
"firstName":"Johsssn",
"lastName":"Jossnes",
"joined":2010
});
Your array is actually data.users, not data.
So use this instead:
var data = {users: []};
data.users.push({
"firstName":"Johsssn",
"lastName":"Jossnes",
"joined":2010
});
var data = {users: []};
data.users.push({
"firstName":"Johsssn",
"lastName":"Jossnes",
"joined":2010
});
Your data object contains one property, users, which is an array of users, so you need to push into it:
data.users.push({
"firstName":"Johsssn",
"lastName":"Jossnes",
"joined":2010
});