[
[
{"path":"path2","value":"kkk"},
{"path":"path0","value":"uuu"},
{"path":"path1","value":"ppp"}
]
]
I get above result from for my manipulation, But I need it as follows.
["path":"path2","value":"kkk"],
["path":"path0","value":"uuu"],
["path":"path1","value":"ppp"]
Here is my code:
$scope.sharePaths[d.id] = []
d.conf.paths = []
$scope.sharePaths[d.id][index] = []
commaPath = 'kkk,uuu,ppp'
a = commaPath.split(',')
for key of a
value = a[key]
$scope.sharePaths[d.id][index].push {'path':'path'+key, 'value':a[key]}
d.conf.paths.push {'path':'path'+key, 'value':a[key]}
Just use the first element of your array. The variable data is already formatted correctly. The new format you want is not valid JSON.
var data = [[{"path":"path2","value":"kkk"},{"path":"path0","value":"uuu"},{"path":"path1","value":"ppp"}]];
data = data[0];
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
var data = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue"
:{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text"
:"Size32","price":"22","isSelected":false},{"text":"Size34","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":2,"label":"Color","placeholder":"Select Color","description":"","defaultValue"
:{"text":"Black","price":"10"},"choices":[{"text":"Black","price":"10","isSelected":"true"},{"text"
:"Green","price":"22","isSelected":false},{"text":"Red","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":3,"label":"Rise","placeholder":"Select Rise","description":"","defaultValue"
:{"text":"Low","price":"8"},"choices":[{"text":"High","price":"12","isSelected":"true"},{"text"
:"Low","price":"8","isSelected":false}],"conditionalLogic"
:""}]';
Here I have posted my JSON data. I want to get all the defaultValue in JSON/Array format. My output should be like-
defaultValues:['Size30','Black','Low']
How to manage that in the foreach loop?
my code :
var otherSelectedOption;
angular.forEach(data, function(optionValue, optionKey) {
if (optionValue.defaultValue.text) {
otherSelectedOption = (optionValue.defaultValue.text);
}
selectedOption = {defaultValues: otherSelectedOption};
console.log(selectedOption);
});
Your JSON is not valid, since objects are not separated by comma ,
Suppose this is the JSON
var obj = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue"
:{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text"
:"Size32","price":"22","isSelected":false},{"text":"Size34","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":2,"label":"Color","placeholder":"Select Color","description":"","defaultValue"
:{"text":"Black","price":"10"},"choices":[{"text":"Black","price":"10","isSelected":"true"},{"text"
:"Green","price":"22","isSelected":false},{"text":"Red","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":3,"label":"Rise","placeholder":"Select Rise","description":"","defaultValue"
:{"text":"Low","price":"8"},"choices":[{"text":"High","price":"12","isSelected":"true"},{"text"
:"Low","price":"8","isSelected":false}],"conditionalLogic"
:""}]';
try
var arr = JSON.parse(obj).map( function(item){
return item.defaultValue;
});
My data is in the following format..
var data= [['typeName', 'valueName'], ['type1', 'value1'],
['type1', 'value2'],['type2', 'value3'],['type2', 'value4']]
I wish to transform the above data to data as below..
var resultdata=[{'typeName':'type1','valueName':['value1','value2']},
{'typeName':'type2','valueName':['value3','value4']}]
Basically I pick up distinct 'typeName' values and then group 'valueName' values by 'typeName' values.
I would preferably use only knockoutjs, lodash or underscorejs as my soln already uses them but I'm open to other solutions as well..
All help is sincerely appreciated
Thanks
I think this solution using underscore should do the trick:
var result= _.chain(data)
.rest()
.groupBy( value => value[0])
.map( (value,key) => ({ [data[0][0]]: key, [data[0][1]]: _.map(value, val => val[1])}))
.value();
This solution uses rest to skip the first item in the data array (the type descriptors). The array is then grouped by the first value in the array (the type) and the mapping returns the grouping in the required form using es6 object initializer notation.
Given the result as:
var resultdata=[
{'typeName':'type1'},{'valueName':['value1','value2']},
{'typeName':'type2'},{'valueName':['value3','value4']}
]
I'm going to call 'typeName' the category and 'valueName' the items.
Since the original data look like this:
var data= [
['typeName', 'valueName'],
['type1', 'value1'],
['type1', 'value2'],
['type2', 'value3'],
['type2', 'value4']
]
It is clear there is a pattern. The first row of data is what we'll use as labels for category and items. All the remaining data represent the values being used inside category and items.
The first step is to extract the labels:
var categoryLabel = data[0][0];
var itemLabel = data[0][1];
Next, the unique categories will need to be determined, so we'll use reduce to build an array of unique categories:
var categories = data
.filter(function(row, i) { return i > 0 }) // remove the labels
.reduce(function(arrCategories, currRow) {
// Add the current rows' category if it doesn't already exist
var currCategory = currRow[0];
if (arrCategories.indexOf(currCategory) === -1) {
return arrCategories.concat(currCategory);
}
return arrCategories;
}, [])
Now that you have a set of categories, you just need to iterate over each one to find all items that belong to it:
var valuesByCategory = {};
categories.forEach(function(category) {
// find all the data items that match the category
var items = data
.filter(function(row) { return row[0] === category; })
.reduce(function(arrItems, currRow) {
var currItem = currRow[1];
if (arrItems.indexOf(currItem) === -1) {
return arrItems.concat(currItem);
}
return arrItems;
}, []);
valuesByCategory[category] = items;
});
Now that all the data has been parsed out, the only thing left to do is build the resultant array:
var resultdata = [];
// iterate through each of the categories
categories.forEach(function(category) {
// using the category label, output an object with the label and category
var categoryObj = {};
categoryObj[categoryLabel] = category;
resultdata.push(categoryObj);
// Next, create a items object containing all the values
var itemsObj = {};
itemsObj[itemLabel] = valuesByCategory[category];
resultdata.push(itemsObj);
}
and that's it :)
The best part is that you don't need any external libraries. This is all ES2015 javascript!
Here is a lodash version of Gruff Bunnies solution:
var data= [['typeName', 'valueName'], ['type1', 'value1'], ['type1', 'value2'],['type2', 'value3'],['type2', 'value4']]
var names = data[0]
var values = _.tail(data)
console.log(JSON.stringify(
_(values)
.groupBy(0)
.map( (value, key) => ({ [names[0]]: key, [names[1]]: _.map(value, 1)}) )
.value()
))
https://jsfiddle.net/nmf1fdf5/
How can I convert the following data structure:
var data = [ [ { time: 1, speed : 20 } ] ];
to
var data = [ { time: 1, speed: 54 } ];
I just want to remove the array.
As the data is an array, you just want to select the first element of the outer array
so the solution would be
var data = [[{time:1,speed:20}]]; // Or whatever the data is
data = data[0];
Or if you're accessing the data via another object
var data = yourObject[0];
Try this :
JSON.stringify(data).substr(1,JSON.stringify(data).length-2);