I have a json file array with data
and I want to use it in a jquery array.
My json file is like this;
[{"id":"1","value":"0.00","score":"a"},
{"id":"2","value":"0.00","score":"c"},
{"id":"3","value":"12.56","score":"e"}]
and then my jquery array outcome i want should be like this (but missing the score and value data.
var setup = [
{
"type": "single",
"subtype": {
"type": "Point",
"score": use 'score' of the json file
},
"properties": {
"text": use 'value' of the json file,
"height": 60
}
},
{
"type": "single",
"subtype": {
"type": "Point",
"score": use score of the json file
},
"properties": {
"text": use value of the json file,
"height": 60
}
}
];
Below I made an attemp to set up a jquery array but i am mnot so good in this. I think i have to use a double $each? but how do I make the array?
var setup = [];
// FETCHING DATA FROM JSON FILE
$.getJSON("results.json", function(data) {
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
var test = "";
$.each(value, function(index, obj) {
});
});
setup.push(setup);
});
Thanks in advance :)
You could use Array.prototype.map() method to get the result.
const data = [
{ id: '1', value: '0.00', score: 'a' },
{ id: '2', value: '0.00', score: 'c' },
{ id: '3', value: '12.56', score: 'e' },
];
const ret = data.map((x) => ({
type: 'single',
subtype: {
type: 'Point',
score: x.score,
},
properties: {
text: x.value,
height: 60,
},
}));
console.log(ret);
You can use one each loop and pass the object with the elements you need. Check the below example:
var jsonData = [{
"id": "1",
"value": "0.00",
"score": "a"
},
{
"id": "2",
"value": "0.00",
"score": "c"
},
{
"id": "3",
"value": "12.56",
"score": "e"
}
]
var setup = [];
// FETCHING DATA FROM JSON FILE
$.each(jsonData, function(key, value) {
var test = "";
d = {
"type": "single",
"subtype": {
"type": "Point",
"score": value.score
},
"properties": {
"text": value.value,
"height": 60
}
};
setup.push(d)
});
console.log(setup)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Related
I am trying to extract multiple values from multiple JSON arrays to create a pie chart.
The below function only able to get a single value but what I want is to get all values from those arrays for example, tag should return "untagged","HK_Online","HK_Order/Change address" but it only return "HK_Online" at the moment.
My function node
var value = msg.payload.lines[0][1].value;
var tag = msg.payload.lines[1][0].value;
msg.topic = tag;
msg.payload = value;
return msg;
JSON data
{
"axes": {
"x": [
{ "name": "Tag","type": "string" },
{ "name": "Total","type": "number" },
{ "name": "Percentage","type": "percent" },
{ "name": "Delta", "type": "delta" }
]
},
"lines": [
[
{ "type": "string","value": "Untagged" },
{ "type": "number","value": 1 },
{ "type": "percent","value": 20 },
{ "type": "delta", "value": 100 }
],
[
{ "type": "string","value": "HK_Online" },
{ "type": "number","value": 4 },
{ "type": "percent","value": 80 },
{ "type": "delta","value": 100 }
],
[
{ "type": "string","value": "HK_Order/Change address" },
{ "type": "number","value": 1 },
{ "type": "percent","value": 20 },
{ "type": "delta","value": 100 }
]
]
}
You can use map method to create new array from the lines array
let lines = msg.payload.lines
let tag = lines.map(item => item[0].value)
let value = lines.map(item => item[1].value)
This is a nested json file and I am trying to arrange it in a readable format to display in a table
I tried to manually put all the keys and values with in a for loop but there should be an elegant way to achieve this and hence I am reaching SO.
The actual JSON is quite a nested one and needed time to execute data with 500k rows
The result should be enhanced JSON with parent values appearing for child values as well
var property = {
"data": [{
"ID": "123456",
"name": "Coleridge st",
"criteria": [
{
"type": "type1",
"name": "name1",
"value": "7",
"properties": []
},
{
"type": "type2",
"name": "name2",
"value": "6",
"properties": [
{
"type": "MAX",
"name": "one",
"value": "100"
}, {
"type": "MIN",
"name": "five",
"value": "5"
}
]
},
{
"type": "type3",
"name": "name3",
"value": "5",
"properties": [{
"type": "MAX1",
"name": "one6",
"value": "1006"
}, {
"type": "MIN2",
"name": "five6",
"value": "56"
}]
}
]
},
{
"ID": "456789",
"name": "New Jersy",
"criteria": [
{
"type": "type4",
"name": "name4",
"value": "6",
"properties": [{
"type": "MAX12",
"name": "one12",
"value": "10012"
}, {
"type": "MIN23",
"name": "five12",
"value": "532"
}]
}
]
}]
};
var output = [];
property.data.forEach(function (users) {
var multirows = {
id: users.ID,
name: users.name,
};
for (var i = 0; i < users.criteria.length; i++) {
var criterias = {
type: users.criteria[i].type,
name: users.criteria[i].name,
value: users.criteria[i].value,
}
var mat_contacts_rows;
if (!isEmpty(users.criteria[i].properties)) {
for (var j = 0; j < users.criteria[i].properties.length; j++) {
var property = {
type: users.criteria[i].properties[j].type,
name: users.criteria[i].properties[j].name,
value: users.criteria[i].properties[j].value
};
mat_contacts_rows = { ...multirows, ...{ criteria: criterias }, ...{ properties: property } };
output.push(mat_contacts_rows);
}
} else {
var property = [];
mat_contacts_rows = { ...multirows, ...{ criteria: criterias }, ...{ properties: property } };
output.push(mat_contacts_rows);
}
}
});
console.log(JSON.stringify(output, undefined, 2))
function isEmpty(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key))
return false;
}
return true;
}
I think this could be a great exercise to you to don't answer your question but to give you some tips. You should first look at : Lodash wish has a bunch of usefull method to help you doing what you'r trying to do.
In a second time you should avoir using .forEach or for loops and try using Array.prototype.map or Array.prototype.reduce
I am trying to count the values a json array.
I want to count the number of id's in the data array of "sierra" if "beta = b". Hence checking the value of data[].beta against the environment variable ("B") set to value 'b'.
The issue here is I do not have "sierra" in every iteration of data[].
{
"data": [{
"alpha": "a",
"beta": "b",
"delta": {
"cat": "dog"
},
"gamma": {
"sierra": {
"data": [
{
"type": "alphabet",
"id": "a"
},
{
"type": "alphabet",
"id": "b"
}
]
}
}
},
{
"alpha": "a",
"beta": "b",
"delta": {
"cat": "dog"
},
"bravo": {
"data": [
{
"type": "number",
"id": "1"
},
{
"type": "number",
"id": "2"
}
]
}
}
},
{
"alpha": "x",
"beta": "y",
"delta": {
"cat": "dog"
},
"gamma": {
"sierra": {
"data": [
{
"type": "alphabet",
"id": "c"
},
{
"type": "alphabet",
"id": "d"
}
]
}
}
}]
}
Above json is the response body I see in postman. "loop" is the count of my "for" loop.
EDIT 1:
I've tried this:
1. pm.response.json().data[loop].gamma.sierra.data().id).size()
2. for(var loop =0; loop < pm.response.json().data.length; loop++)
{
if(pm.response.json().data[loop].beta===pm.variables.get("B"))
{
pm.response.json().data.map((item, loop) => {
if(item.gamma){ // check if gamma key is present
console.log(item.gamma.sierra.filter(data =>data.id
).length); //
}
});
result=true;
break;
}
}
pm.expect(true).to.eql(result);
Expected: 2
Actual: TypeError: Cannot read property 'sierra' of undefined
Actual: item.relationships.apps.filter is not a function
You could take a dynamic apporach and hand over the key of the object where you like to count a certain inner key.
function count(object, key, subKey) {
const noObject = o => !o || typeof o !== 'object';
function subCount(object) {
if (noObject(object)) return 0;
if (subKey in object) return 1;
return Object.values(object).reduce((s, o) => s + subCount(o), 0);
}
if (noObject(object)) return 0;
if (key in object) return subCount(object[key]);
return Object.values(object).reduce((s, o) => s + count(o, key, subKey), 0);
}
var data = { data: [{ alpha: "a", beta: "b", delta: { cat: "dog" }, gamma: { sierra: { data: [{ type: "alphabet", id: "a" }, { type: "alphabet", id: "b" }] } } }] };
console.log(count(data, 'sierra', 'id')); // 2
You can access it like this. If you have multiple data records you can use each loop to calculate as well.
a = {
"data": [
{
"alpha": "a",
"beta": "b",
"delta": {
"cat": "dog"
},
"gamma": {
"sierra": {
"data": [
{
"type": "alphabet",
"id": "a"
},
{
"type": "alphabet",
"id": "b"
}
]
}
}
}
]
}
console.log(a.data[0].gamma.sierra.data.length);
You can use below code:
pm.response.json().data[0].gamma.sierra.data.filter( d => d.id ).length
Hope it helps.
pm.response.json().data.map((item, loop) => {
if(item.beta === "b" && item.gamma){ // check if gamma key is present
console.log(item.gamma.sierra.data.filter(data => data.id).length); //
}
});
Jsfiddle
I have a data object with following contents:
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
I want to remove block that has key yellow, by looping over blocks, rest of the data should be preserved as is. So expected end result would be
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
Data is dynamic so I dont know what would be returned, it might have a match for my condition or it might not.
I've tried a bunch of approaches but nothing seems to have worked so far. I can use lodash too if its any easier. None of those seems to be working. Any help/direction is appreciated
1. Using **delete**
const deleteUnwantedBlock = contentObj => {
const updatedData = contentObj;
const blocks = _.get(updatedData, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
delete updatedData.block;
}
});
return updatedData;
};
console.log(deleteUnwantedBlock(data.content));```
2. Using rest operator:
const deleteUnwantedBlock = contentObj => {
const blocks = _.get(contentObj, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
let { block, ...restOfTheData } = updatedData;
}
return { ...updatedEntry };
});
};
console.log(deleteUnwantedBlock(data.content));
You just need to filter:
const obj = {
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
};
obj.content.blocks = obj.content.blocks.filter(({ key }) => key !== 'yellow');
console.log(obj);
This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 5 years ago.
{
"Data": [{
"Rsrc": "DB",
"status": "100",
"TimeStamp": "TimeStamp1"
},
{
"Rsrc": "Oracle",
"status": "0",
"TimeStamp": "TimeStamp1"
},
{
"Rsrc": "Oracle",
"status": "100",
"TimeStamp": "TimeStamp2"
},
{
"Rsrc": "DB",
"status": "100",
"TimeStamp": "TimeStamp2"
}
]
}
(Where TimeStamp1 andTimeStamp2 are valid time stamps)
I'm getting the above data using a Rest Service. I need to
Showcase it in a different manner. Have to convert it this way that I'll get the response in 2 variables called
Category = [TimeStamp1,TimeStamp2]
and
Data= [{
name: 'DB',
data: [100, 100]
}, {
name: 'Oracle',
data: [0, 100]
}]
Thanks in Advance
The first one is easy, just map the data array to one containing only the timestamps and pipe it into a Set
const Category = Array.from(new Set(obj.Data.map(datum => datum.TimeStamp)))
The second will require you to reduce the data to a map of Rsrc to a status array which you can then transform into an array
const obj = {"Data":[{"Rsrc":"DB","status":"100","TimeStamp":"TimeStamp1"},{"Rsrc":"Oracle","status":"0","TimeStamp":"TimeStamp1"},{"Rsrc":"Oracle","status":"100","TimeStamp":"TimeStamp2"},{"Rsrc":"DB","status":"100","TimeStamp":"TimeStamp2"}]}
const Data = Array.from(obj.Data.reduce((map, datum) => {
let data = map.get(datum.Rsrc) || []
return map.set(datum.Rsrc, data.concat(datum.status))
}, new Map())).map(entry => ({
name: entry[0],
data: entry[1]
}))
console.info('Data', Data)
var input ={
"Data": [{
"Rsrc": "DB",
"status": "100",
"TimeStamp": "TimeStamp1"
},
{
"Rsrc": "Oracle",
"status": "0",
"TimeStamp": "TimeStamp1"
},
{
"Rsrc": "Oracle",
"status": "100",
"TimeStamp": "TimeStamp2"
},
{
"Rsrc": "DB",
"status": "100",
"TimeStamp": "TimeStamp2"
}
]
};
var data= input.Data;
var Category =[];
var Data =[];
var DataIndex = [];
data.forEach(function(i)
{
if(Category.indexOf(i.TimeStamp)==-1) Category.push(i.TimeStamp);
var idx=DataIndex.indexOf(i.Rsrc)
if(idx==-1) {
DataIndex.push(i.Rsrc);
Data.push({name:i.Rsrc,data:[i.status]});
} else {
Data[idx].data.push(i.status);
}
});
console.log(Category);
console.log(Data);
I looped over your data and built the two new arrays. I used a third rsrc array to help to determine which position in the data array to add new items too.
var test = {
"Data": [{
"Rsrc": "DB",
"status": "100",
"TimeStamp": 'TimeStamp1'
},
{
"Rsrc": "Oracle",
"status": "0",
"TimeStamp": 'TimeStamp1'
},
{
"Rsrc": "Oracle",
"status": "100",
"TimeStamp": 'TimeStamp2'
},
{
"Rsrc": "DB",
"status": "100",
"TimeStamp": 'TimeStamp2'
}
]
};
var category = [];
var data = [];
var rsrc = [];
test['Data'].forEach(function( item ){
if( category.indexOf( item['TimeStamp'] ) === -1 ){
category.push( item['TimeStamp'] );
}
if( rsrc.indexOf( item[ 'Rsrc' ] ) === -1 ){
rsrc.push( item[ 'Rsrc' ] );
}
var pos = rsrc.indexOf( item[ 'Rsrc' ] );
// set as itself or an object if it's not yet been set
data[pos] = data[pos] || {};
data[pos].name = item[ 'Rsrc' ];
data[pos].data = data[pos].data || [];
data[pos].data.push( item.status );
});
console.log( category );
console.log( data );
Edit fixed issue with repeated categories, thanks to #yashgarg1232