Getting Multiple unorganized values from JSON in Javascript - javascript

I have the following javascript
{
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":"
[{\"TagId\":\"T1\",\"TagName\":\"test2\",\"TagType\":1},
{\"TagId\":\"T2\",\"TagName\":\"test1\",\"TagType\":1}]"
}
What I am trying to do is, to use javascript to get the TagName from Tags section
When i use JSON.parse(Obj.Tags); I get everything under Tags section where i only want TagName
Is it possible?

It's possible. You can use the .map function.
var tagNames = obj.Tags.map(function(x){
return x.TagName;
});
var obj = {
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":
[{"TagId":"T1","TagName":"test2","TagType":1},
{"TagId":"T2","TagName":"test1","TagType":1}]
};
var tagNames = obj.Tags.map(function(x){
return x.TagName;
})
console.log(tagNames)

I think I probably get what your question is.
Would you like your Tags to be only array of TagName?
Here's example code:
var Obj = {
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":"[{\"TagId\":\"T1\",\"TagName\":\"test2\",\"TagType\":1}, {\"TagId\":\"T2\",\"TagName\":\"test1\",\"TagType\":1}]"
}
// Get Tags data to array object
var Tags = JSON.parse(Obj.Tags);
// Get simple array of TagNames
var TagNames = Tags.map(x=>x.TagName);
console.log(TagNames);
// Get array of objects with only TagName key value pair
var TagNamesFormat2 = Tags.map(function(x){
return {"TagName" : x.TagName}
});
console.log(TagNamesFormat2);

You can use map() on Tags
// Parsed object
var data = {
"Exists": true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,
"Fav":false,
"Shield":false,
"Tags": [
{"TagId":"T1","TagName":"test2","TagType":1},
{"TagId":"T2","TagName":"test1","TagType":1}
]
}
console.log(data.Tags.map(tag => tag.TagName));

Try tags.map(a => a.TagName);
var myObj = {
"Exists":true,
"Id":"c558eedac67244908fc127d028663b96",
"Type":6,"Fav":false,
"Shield":false,
"Tags":"[{\"TagId\":\"T1\",\"TagName\":\"test2\",\"TagType\":1}, {\"TagId\":\"T2\",\"TagName\":\"test1\",\"TagType\":1}]"
};
var tags = JSON.parse(myObj.Tags);
var tagNames = tags.map(a => a.TagName);
console.log(tagNames);

Related

JS converting an array to a json linked list?

I am new to JS and the concepts of organising data elude me a little, trying to take data from a specific array format (as this is what I have to work with) and output it into another specific JSON format.
This is to pass data to the D3 sankey module
https://github.com/d3/d3-plugins/blob/master/sankey/sankey.js
I can't figure out is how to add the index of the node into the links, rather than the name.
Really I am just totally lost with it!
I made a fiddle here:
https://jsfiddle.net/adamdavi3s/kw3jtzx4/
Below is an example of the data and the output required
var data= [
{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var output= {
"nodes":[
{"name":"Agricultural 'waste'"},
{"name":"Bio-conversion"},
{"name":"Electricity grid"},
{"name":"Losses"},
{"name":"Liquid"}
],
"links":[
{"source":0,"target":1,"value":124.729},
{"source":1,"target":2,"value":0.597},
{"source":1,"target":3,"value":26.862},
{"source":1,"target":4,"value":280.322},
{"source":3,"target":4,"value":280.322}
]
};
Here is my code from the fiddle thusfar
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source};
var found = jQuery.inArray(node, sourceArray);
if (found < 0) {
// Element was not found, add it.
sourceArray.push(node);
}
}
console.log(sourceArray);
In javascript:
[ ] annotations are used to describe an Array, like:
var names=["John","Lisa"]
{ } Its are used to describe an Object
var person = {"name" : "John", "age" : 23}
You can use them inside one another
var people=[{"name" : "John", "age" : 23},{"name" : "Lisa", "age" : 44}]
Try this:
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
var linkArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source,};
var link= {
"source":i,
"target":data[i].target,
"value":data[i].value,
};
var found = jQuery.inArray(node, sourceArray);
if (found >= 0) {
// Element was found, remove it.
sourceArray.splice(found, 1);
linkArray.splice(found, 1);
} else {
// Element was not found, add it.
sourceArray.push(node);
linkArray.push(link);
}
}
finalArray={"nodes": sourceArray,"links": linkArray}
console.log(finalArray);
https://jsfiddle.net/9x4rdyy7/
Array.reduce() is perfect for this use case ;)
Take a look.
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var output = data.reduce(function(result, item){
for(key in search = ['source','target']) {
var value = item[search[key]];
if(! result.index.hasOwnProperty(value)){
result.index[value] = Object.keys(result.index).length;
result.nodes.push({name: value});
}
}
result.links.push({
source: result.index[item.source],
target: result.index[item.target],
value: Number(item.value)
});
return result;
}, {nodes: [], links: [], index: {}});
delete output.index;
console.log(output);

Array push behavior

Although I have some basic JavaScript background, I stumbled upon this code that I wrote:
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}]
var tempArr=[];
var table=[];
var dataArr = Object.keys(data).map(function(k) { return data[k] });
dataArr.forEach(function(user) {
tempArr[0]=user.fName;
tempArr[1]=user.lName;
tempArr[2]=user.email;
tempArr[3]=user.age;
table.push(tempArr);
console.log('table'+JSON.stringify(table));
});
In the final loop, I expected table to contain the arrays for Tom, Pat, and Sam . Instead, this is what I got:
table[["Tom","Moody","Tom#example.com",30]]
table[["Pat","Smith","pat#example.com",32],["Pat","Smith","pat#example.com",32]]
table[["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28]]
table[["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28],["Sam","Dawn","sam#example.com",28]]
Why is push() replacing the previous entry in table? Any help will be highly appreciated.
The others already pointed out problems in your code.
However, you also make things more complicated than necessary. You can just do this:
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}];
var table = data.map(function(user) {
return [
user.fName,
user.lName,
user.email,
user.age,
];
});
console.log(table);
Or if you use ES6:
var table = data.map(user => [ user.fName, user.lName, user.email, user.age ];
You don't need to write all the boilerplate code by hand. Use a proper array iterator (map in your case).
var table = data.map(function(user) {
return [user.fName, user.lName, user.email, user.age];
});
Obviously map isthe way to go for the sake of functional approach however if you like imperative styles one simplistic way could be using for of loop as follows.
var data = [{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}],
table = [];
for (var user of data) table.push([user.fName,user.lName,user.email,user.age]);
console.log(table);
Problem here is not with push. Variable in javascript store reference to array. And in table you are pushing reference to same array tempArr. You need to create new array before pushing it or create deep copy of array before pushing it.
Example
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}]
var table=[];
var dataArr = Object.keys(data).map(function(k) { return data[k] });
dataArr.forEach(function(user) {
var tempArr=[];
tempArr[0]=user.fName;
tempArr[1]=user.lName;
tempArr[2]=user.email;
tempArr[3]=user.age;
table.push(tempArr);
console.log('table'+JSON.stringify(table));
});
Well, unlike a lot of other languages, JavaScript has passes everything by reference. That means that when you table.push(tempArr);, you're not actually pushing the values of tempArr, you're pushing a reference to tempArr. So, if you do this:
var a = 'a';
var table = [];
table.push(a);
a = 'b';
console.log(table[0]);
You'll get b as your output. What you want to do is define a new variable to push, like this
var data=[{"_id":"57b3e7ec9b209674f1459f36","fName":"Tom","lName":"Moody","email":"Tom#example.com","age":30},{"_id":"57b3e8079b209674f1459f37","fName":"Pat","lName":"Smith","email":"pat#example.com","age":32},{"_id":"57b3e8209b209674f1459f38","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28},{"_id":"57b3e8219b209674f1459f39","fName":"Sam","lName":"Dawn","email":"sam#example.com","age":28}]
var table=[];
var dataArr = Object.keys(data).map(function(k) { return data[k] });
dataArr.forEach(function(user) {
var tempArr=[];
tempArr[0]=user.fName;
tempArr[1]=user.lName;
tempArr[2]=user.email;
tempArr[3]=user.age;
table.push(tempArr);
});
console.log('table'+JSON.stringify(table));
var data = [{"_id": "57b3e7ec9b209674f1459f36","fName": "Tom","lName": "Moody","email": "Tom#example.com","age": 30}, {"_id": "57b3e8079b209674f1459f37","fName": "Pat","lName": "Smith","email": "pat#example.com","age": 32}, {"_id": "57b3e8209b209674f1459f38","fName": "Sam","lName": "Dawn","email": "sam#example.com","age": 28}, {"_id": "57b3e8219b209674f1459f39","fName": "Sam","lName": "Dawn","email": "sam#example.com","age": 28}],
table = [];
data.forEach(function(user) {
table.push([user.fName, user.lName, user.email, user.age]);
});
console.log(table);

How to get JSON Data depending on other data values in JavaScript

My Json is like this:
[
{"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
]
I want all the names which have BankOut value as "Y" into an array using JavaScript, in order to use those names in my protractor automation.
You need to use filter method of array. It takes function as it argument. And runs it against each element of array. If function returns true (or other truthy value) then that element stays in newly created array.
var list =[ {"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso ", "CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
];
var onlyBankOutY = list.filter(function (item) {
return item.BankOut === 'Y';
});
document.body.innerHTML = onlyBankOutY.map(function (item) {
return JSON.stringify(item);
}).join('<br>');
var list =[
{"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso ", "CashOut":"Y","BankOut":"","MMT":null}, {"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
];
var names = [];
list.forEach(function(el) {
if (el.BankOut === 'Y') {
names.push(el.name)
}
})

Convert txt to string is not working

I've node application and Inside a folder I've txt file(long...) with content like following
BASH=/bin/sh
BASH_ARGC=()
BASH_ARGV=()
BASH_LINENO=([0]="0")
BASH_VERSINFO=([0]="3" [1]="2" [2]="51" [3]="1" [4]="release" )
BASH_VERSION='3.2.2(1)-release'
CF_INSTANCE_ADDR=10.2.7:501
CF_INSTANCE_INDEX=0
CF_INSTANCE_IP=10.97.27.7
CF_INSTANCE_P='[{external:500,internal:501}]'
COLUMNS=80
I read the txt file content with fs.readFile and I need to update some property there so I think to parse it to json but this is not working
my questions is:
Should I parse it to json? in order to modify some property value
such like
from
CF_INSTANCE_ADDR=10.2.7:501
to
CF_INSTANCE_ADDR=11.3.8:702
Or
CF_INSTANCE_P='[{external:500,internal:501}]'
to
CF_INSTANCE_P='[{external:100,internal:200}]'
Etc...
There is other better way?
This is what I tried
fs.readFile(filePath, 'utf8').then(function (response) {
var aa = JSON.stringify(response);
//console.log(aa);
var bb = JSON.parse(aa);
console.log(bb);
return response;
}
You can convert the string to an object at which point you can decide how to proceed/tidy up the data:
var obj = {};
str.split(/\n/g).forEach(function (el) {
var spl = el.split('=');
obj[spl[0]] = spl[1];
});
DEMO
So you should be left with an object called obj:
var obj = {
"BASH": "/bin/sh",
"BASH_ARGC": "()",
"BASH_ARGV": "()",
"BASH_LINENO": "([0]",
"BASH_VERSINFO": "([0]",
"BASH_VERSION": "'3.2.2(1)-release'",
"CF_INSTANCE_ADDR": "10.2.7:501",
"CF_INSTANCE_INDEX": "0",
"CF_INSTANCE_IP": "10.97.27.7",
"CF_INSTANCE_P": "'[{external:500,internal:501}]'",
"COLUMNS": "80"
}
You can now access the values of each key using either dot or bracket notation:
obj.BASH_VERSION // '3.2.2(1)-release'
obj['BASH_VERSION'] // '3.2.2(1)-release'
Here I'll remove those single quotes from BASH_VERSION:
obj.BASH_VERSION = obj.BASH_VERSION.replace("'", "");

How to push new key/value pair into external json file? [duplicate]

I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
I want to add a new item to the array, such as
{"teamId":"4","status":"pending"}
to end up with
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.
JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.
elementToPush = [1, 2, 3]
if (!obj.arr) this.$set(obj, "arr", [])
obj.arr.push(elementToPush)
(This answer may not be relevant to this particular question, but may help
someone else)
Use spread operator
array1 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Organization"
}
];
array2 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Division"
}
];
array3 = [
{
"column": "Level",
"operator": "=",
"value": "Country"
}
];
console.log(array1.push(...array2,...array3));
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<i class="fa fa-shopping-cart"></i>Add to cart'
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
How do I store a simple cart using localStorage?

Categories

Resources