JSON parser with Array Comma Separated Javascript - javascript

i have a JSON structure which looks like this.
"content" : {
"state" : {
"Idle" : [
[
78.366666667,
1436955825
],
[
71.281111111,
1436955840
],
[
70.41,
1436955855
],
[
74.283333333,
1436955870
],
[
76.411111111,
1436955885
]
]
} }
What i have to do is to parse this value. i have to separate comma separated value into x and y. i have to parse these values and separate them. i am having problem issue parsing them
it should look like this
"Idle" : [
{
"x" : 78.366666667,
"y" :1436955825
},
{
"x" :71.281111111,
"y" :1436955840
},
{
"x" :70.41,
"y" :1436955855
},
{
"x" :74.283333333,
"y" :1436955870
},
{
"x" :76.411111111,
"y" :1436955885
}
]

Map the ...Idle elements to objects (see MDN for Array.map):
test = {
content: {
state: {
Idle: [
[
78.366666667,
1436955825
],
[
71.281111111,
1436955840
],
[
70.41,
1436955855
],
[
74.283333333,
1436955870
],
[
76.411111111,
1436955885
]
]
}
}
};
test.content.state.Idle = test.content.state.Idle.map(
function (v) {
return { x: v[0], y: v[1] };
}
);
document.querySelector("#result").textContent = JSON.stringify(test, null, " ");
<pre id="result"></pre>

var container = {
"content": {
"state": {
"Idle": [
[
78.366666667,
1436955825
],
[
71.281111111,
1436955840
],
[
70.41,
1436955855
],
[
74.283333333,
1436955870
],
[
76.411111111,
1436955885
]
]
}
}
};
var _oldIdle = container.content.state.Idle,
_newIdle = [];
for (var i = 0; i < _oldIdle.length; i++) {
_newIdle.push({
x: _oldIdle[i][0],
y: _oldIdle[i][1]
});
}
container.content.state.Idle = _newIdle;

Try this way:
var json = {
"content": {
"state": {
"Idle": [
[
78.366666667,
1436955825
],
[
71.281111111,
1436955840
],
[
70.41,
1436955855
],
[
74.283333333,
1436955870
],
[
76.411111111,
1436955885
]
]
}
}
};
var newObj = {},
arr = [];
$.each(json.content.state.Idle, function(i, item) {
arr.push({x: item[0], y: item[1]});
});
newObj.idle = arr;
console.log(newObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If you have JSON string you can use JSON.parse with reviver function
var json = '{"content":{"state":{"Idle":[[78.366666667,1436955825],[71.281111111,1436955840],[70.41,1436955855],[74.283333333,1436955870],[76.411111111,1436955885]]}}}';
var result = JSON.parse(json, function(k, v) {
if ((v instanceof Array) && (isFinite(Number(k)))) {
//if array with coordinates - return object instead
return {
x: v[0],
y: v[1]
};
}
return v;
})
console.log(result);
document.getElementById('r').innerHTML = JSON.stringify(result,null,2)
<pre id='r'></pre>

With UnderscoreJS is simple:
JSFiddle
var values = {
"content": {
"state": {
"Idle": [
[
78.366666667,
1436955825],
[
71.281111111,
1436955840],
[
70.41,
1436955855],
[
74.283333333,
1436955870],
[
76.411111111,
1436955885]
]
}
}
};
var newValues = _.map(values.content.state.Idle, function (value, key) {
return {x: value[0], y: value[1]};
});
console.log(newValues);

Related

How to convert nested array of object into arraylist in javascript?

i have a nested array of object and i want to convert in arraylist like this :
this is my data array of object :
{
"status": true,
"message": "",
"data": [{
"pasien_docs": [{
"ecg": null,
"date": "2020-01-21T05:22:01.901Z"
}, {
"ecg": 1.03,
"date": "2020-01-21T05:22:02.979Z"
}, {
"ecg": 1.04,
"date": "2020-01-21T05:22:04.053Z"
}, {
"ecg": 1.04,
"date": "2020-01-21T05:22:05.126Z"
},
]
}
]
}
and i want change convert to array like this :
{
"status": true,
"message": "",
"data": [
[
"2020-01-21T05:22:01.901Z",
null
],
[
"2020-01-21T05:22:01.901Z",
1, 03
]
[
"2020-01-21T05:22:01.901Z",
1.04
]
[
"2020-01-21T05:22:01.901Z",
1.04
]
]
}
i try using map to convert on result like this :
result = result.map((u, i) => [
u.pasien_docs[i].date,
u.pasien_docs[i].ecg,
]);
but why i only get result data of one array not four data ? help me please, thankyou..
{
"status": true,
"message": "",
"data": [
[
"2020-01-21T05:22:01.901Z",
null
]
]
}
Would that work for you?
const src = {"status":true,"message":"","data":[{"pasien_docs":[{"ecg":null,"date":"2020-01-21T05:22:01.901Z"},{"ecg":1.03,"date":"2020-01-21T05:22:02.979Z"},{"ecg":1.04,"date":"2020-01-21T05:22:04.053Z"},{"ecg":1.04,"date":"2020-01-21T05:22:05.126Z"},]}]},
result = {
...src,
data: src.data[0].pasien_docs.map(Object.values)
}
console.log(result)
.as-console-wrapper{min-height:100%;}
If you dont wanna use spread operator, this can also do the trick for you
const source = {"status":true,"message":"","data":[{"pasien_docs":[{"ecg":null,"date":"2020-01-21T05:22:01.901Z"},{"ecg":1.03,"date":"2020-01-21T05:22:02.979Z"},{"ecg":1.04,"date":"2020-01-21T05:22:04.053Z"},{"ecg":1.04,"date":"2020-01-21T05:22:05.126Z"},]}]}
const result = Object.assign({}, source, {
data: source.data[0].pasien_docs.map(Object.values)
})
console.log(result)
let obj = {
status: true,
message: "",
data: [
{
pasien_docs: [
{
ecg: null,
date: "2020-01-21T05:22:01.901Z",
},
{
ecg: 1.03,
date: "2020-01-21T05:22:02.979Z",
},
{
ecg: 1.04,
date: "2020-01-21T05:22:04.053Z",
},
{
ecg: 1.04,
date: "2020-01-21T05:22:05.126Z",
},
],
},
],
};
var finalobj = JSON.parse(JSON.stringify(obj));
var innerobj = obj.data;
var intermd = innerobj.map((data) => {
return data.pasien_docs;
});
finalarray = intermd[0].map((val) => {
return [val.ecg, val.date];
});
console.log(obj);
finalobj.data[0].pasien_docs=finalarray;
console.log(finalobj);

How to get index of a nested field in JSON object using Loadash?

I have JSON object that looks like the snippet below.
I can navigate to the fields that I am interested to query, which match the pattern useful*
contents[0].mainArea[1].rec[0].attributes['useful.k1']
contents[0].mainArea[1].rec[1].attributes['useful.k1']
Is it possible to write a Lodash command that can extract/return the indices in bold above? I need the indices as I will later use these indices to create an assertion.
I am not sure where to start looking. Any ideas as to which commands I need to consider will be greatly appreciated.
{
"contents": [
{
"leftArea": [],
"mainArea": [
{
"key11": "val11",
"key12": [
{
"subkey11": "subValue11",
"subkey12": "subValue12"
},
{
"subkey21": "subValue21",
"subkey22": "subValue22"
}
]
},
{
"key21": "val21",
"rec": [
{
"attributes": {
"useful.k1": [
"value"
],
"useful.k2": [
"value"
],
"useful.k3": [
"value"
]
}
},
{
"attributes": {
"useful.k1": [
"value"
],
"useful.k2": [
"value"
],
"useful.k3": [
"value"
]
}
},
{
"notuseful": "value",
"notuseful2": [
{
"key1": "value",
"key2": "value"
},
{
"key1": "value",
"key2": "value"
},
{
"key1": "value",
"key2": "value"
}
]
}
]
}
]
}
]
}
I don't know if there is any specific lodash command for your problem, but you can use some functions to find your desired indices by some code like below:
const keys = require('lodash/keys');
function findUsefulKeys(data) {
const indices = [];
for (let i = 0; i < data.contents.length; i++) {
const mainAreaIndiesWithUsefulKeys = findUsefulKeysInContent(data.contents[i]);
if (mainAreaIndiesWithUsefulKeys.length > 0) {
indices.push({
contentIndex: i,
mainAreaIndices: mainAreaIndiesWithUsefulKeys
});
}
}
return indices;
}
function findUsefulKeysInContent(content) {
const mainAreaIndices = [];
if (!content.mainArea || !content.mainArea.length || content.mainArea.length === 0) {
return mainAreaIndices;
}
for (let i = 0; i < content.mainArea.length; i++) {
const recIndices = findRecsWithUsefulKeysInMainArea(content.mainArea[i]);
if (recIndices.length > 0) {
mainAreaIndices.push({
mainAreaIndex: i,
recIndices: recIndices
});
}
}
return mainAreaIndices;
}
function findRecsWithUsefulKeysInMainArea(mainArea) {
const recIndices = [];
if (!mainArea.rec || !mainArea.rec.length || mainArea.rec.length === 0) {
return recIndices;
}
for (let i = 0; i < mainArea.rec.length; i++) {
if (recHasUsefulKeys(mainArea.rec[i])) {
recIndices.push(i);
}
}
return recIndices;
}
function recHasUsefulKeys(rec) {
if (!rec || !rec.attributes) {
return false;
}
const attributeKeys = keys(rec.attributes);
for (let i = 0; i < attributeKeys.length; i++) {
if (attributeKeys[i].startsWith('useful')) {
return true;
}
}
return false;
}
// data is you json data
const data = require('./data');
console.log(JSON.stringify(findUsefulKeys(data)));
The above code with your example json data will print
[{"contentIndex":0,"mainAreaIndices":[{"mainAreaIndex":1,"recIndices":[0,1]}]}]
You can loop to get the value from JSON like below:
const data = {
"contents": [
{
"leftArea": [],
"mainArea": [
{
"key11": "val11",
"key12": [
{
"subkey11": "subValue11",
"subkey12": "subValue12"
},
{
"subkey21": "subValue21",
"subkey22": "subValue22"
}
]
},
{
"key21": "val21",
"rec": [
{
"attributes": {
"useful.k1": [
"value"
],
"useful.k2": [
"value"
],
"useful.k3": [
"value"
]
}
},
{
"attributes": {
"useful.k1": [
"value"
],
"useful.k2": [
"value"
],
"useful.k3": [
"value"
]
}
},
{
"notuseful": "value",
"notuseful2": [
{
"key1": "value",
"key2": "value"
},
{
"key1": "value",
"key2": "value"
},
{
"key1": "value",
"key2": "value"
}
]
}
]
}
]
}
]
}
const useful = data.contents[0].mainArea[1].rec;
for(const v in useful)
{
//console.log(useful[v].attributes); // Oject
for( let vv in useful[v].attributes) // for for every single value
{
console.log(useful[v].attributes[vv]);
}
}

Filtering nested nested array

Hi have this array:
[ {
"Navn": "Long Island Iced Tea",
"Nummer": "2",
"Glas i ml": "250",
"Instruktioner": "",
"a": "Hæld is i glasset",
"b": "pynt med en skive lime",
"Ingredienser": [
{
"Type": "Spiritus",
"Del1": [
{
"Cointreau": 20
}
],
"Del2": [
{
"Gin": 20
}
],
"Del3": [
{
"Rom_Lys": 20
}
],
"Del4": [
{
"Tequila": 20
}
],
"Del5": [
{
"Vodka": 20
}
]
},
{
"Type": "Vand/Juice",
"Del1": [
{
"Cola": 40
}
],
"Del2": [
{
"Sprite": 20
}
]
},
{
"Type": "Mixer",
"Del1": [
{
"Lime_Sirup": 20
}
]
}
]
}]
Its for a Cocktailmachine.
And i want to filter it by "Del1" searching for (example) "Rom_Lys" & "Cola" & "Vodka", and then output a new array with these specifications.
I tried searching the forums, but can't seem to find something useful. Played around with filter and includes, but cant come up with anything useful.
Thx!
If you want to get items which are contains Cola, then you can use filter and some methods:
const filterWord = 'Cola';
const result = sampleData.filter(s =>
s.Ingredienser.some(s =>
s.Del1.some( e=> e[filterWord])));
console.log(result);
An example:
let sampleData = [
{
"Navn": "Rom & Cola/ Cuba Libre",
"Nummer": "0",
"Glas i ml": "200",
"Instruktioner": "",
"a": "Hæld is i glasset",
"b": "pynt med en skive citron",
"Ingredienser": [
{
"Type": "Spiritus",
"Del1": [
{
"Rom_Lys": 40
}
]
},
{
"Type": "Vand/Juice",
"Del1": [
{
"Cola": 100
}
]
},
{
"Type": "Mixer",
"Del1": [
{}
]
}
]
},
{
"Navn": "Isbjørn",
"Nummer": "1",
"Glas i ml": "200",
"Instruktioner": "",
"a": "Hæld is i glasset",
"b": "pynt med en skive citron",
"Ingredienser": [
{
"Type": "Spiritus",
"Del1": [
{
"Vodka": 30
}
]
},
{
"Type": "Vand/Juice",
"Del1": [
{
"Sprite": 60
}
]
},
{
"Type": "Mixer",
"Del1": [
{
"Blå_Sirup": 30
}
]
}
]
}];
const filterWord = 'Cola';
const result = sampleData.filter(s => s.Ingredienser.some(s => s.Del1.some( e=> e[filterWord])));
console.log(result);
UPDATE:
If you want to check multiple key, then you can use hasOwnProperty method which checks whether the object contains desired key:
const filters = ['Cointreau', 'Gin', 'Rom_Lys'];
const result = sampleData.filter(s =>
s.Ingredienser.some(ingred => {
return Object.keys(ingred).some(k=> {
if (Array.isArray(ingred[k])) {
return ingred[k].some(s=> filters.some(f=> {
return s.hasOwnProperty(f);
}))
}
});
}
));
And the example:
let sampleData = [ {
"Navn": "Long Island Iced Tea",
"Nummer": "2",
"Glas i ml": "250",
"Instruktioner": "",
"a": "Hæld is i glasset",
"b": "pynt med en skive lime",
"Ingredienser": [
{
"Type": "Spiritus",
"Del1": [
{
"Cointreau": 20
}
],
"Del2": [
{
"Gin": 20
}
],
"Del3": [
{
"Rom_Lys": 20
}
],
"Del4": [
{
"Tequila": 20
}
],
"Del5": [
{
"Vodka": 20
}
]
},
{
"Type": "Vand/Juice",
"Del1": [
{
"Cola": 40
}
],
"Del2": [
{
"Sprite": 20
}
]
},
{
"Type": "Mixer",
"Del1": [
{
"Lime_Sirup": 20
}
]
}
]
}];
const filters = ['Cointreau', 'Gin', 'Rom_Lys'];
const result = sampleData.filter(s =>
s.Ingredienser.some(ingred => {
return Object.keys(ingred).some(k=> {
if (Array.isArray(ingred[k])) {
return ingred[k].some(s=> filters.some(f=> {
return s.hasOwnProperty(f);
}))
}
});
}
));
console.log(result);
Try using following code to filter the array.
var filtered = arr.filter(function(unique) {
for (var index = 0; index < unique.Ingredienser.length; index++) {
if (unique.Ingredienser[index].Del1[0].hasOwnProperty(selectedchoice)) {
return true;
}
}
return false;
});

modify json object and save it

I do have a json array object. I need to modify it then save the modified version on a variable.
the json object
var json = [
{
"Name": "March-2016",
"Elements": [
{
"Name": "aa",
"Elements": [
{
"Name": "ss",
"Data": {
"Test1": [
22
],
"Test2": [
33
],
"Test3": [
44
],
"Test4": [
55
]
}
},
{
"Name": "ssee",
"Data": {
"Test12": [
222
],
"Test22": [
3322
],
"Test32": [
445
],
"Test42": [
553
]
}
}
]
}
]
}
];
need to be modified to
var json = [
{
"Name": "March-2016",
"Elements": [
{
"Name": "aa",
"Elements": [
{
"category": "ss",
"Test1": 22,
"Test2": 33 ,
"Test3":44,
"Test4": 55
},
{
"category": "ssee",
"Test12": 222,
"Test22": 3322 ,
"Test32":445,
"Test42": 553
}
]
}
]
}
];
I have this method but its not doing the job
var saveJson = function(arr) {
var nameValuePairs = [];
for (var i = 0, len = arr.length; i < len; i++) {
var item = arr[i];
if (item.Data) {
var newvar = {
category : item.Name
}
newvar[Object.keys(item.Data)] = Object.values(item.Data);
item = newvar
}
if (item.Elements) {
nameValuePairs = nameValuePairs.concat(saveJson(item.Elements));
}
}
return arr;
};
I need this conversion to be dynamic as for sure I will get bigger json than the posted one
sorry for the confusion and thanks in advance.
The original object is really a mess, but still you just need to step through it and pull out the values you want. This changes the json object in place:
json.forEach(item => {
item.Elements.forEach(Outer_El => {
Outer_El.Elements = Outer_El.Elements.map(item =>{
let obj = {category: item.Name}
Object.keys(item.Data).forEach(key => {
obj[key] = item.Data[key][0]
})
return obj
})
})
})
json should now look like:
[{
"Name":"March-2016",
"Elements":[
{
"Name":"aa",
"Elements":[
{
"category":"ss",
"Test1":22,
"Test2":33,
"Test3":44,
"Test4":55
},
{
"category":"ssee",
"Test1e":224,
"Test2e":334,
"Test3e":443,
"Test4e":554
}
]
}
]
}]
You can use destructuring assignment to get specific property values from an object
{
let {Name:categories, Data:{Test:[Test]}} = json[0].Elements[0].Elements[0];
json[0].Elements[0].Elements[0] = {categories, Test};
}

Remove object from array where sub-object matches a value

I'm currently attempting to sort through some values based on a query string. I'm able to target each target individually in this loop but cannot seem to properly remove them from the array. How can I remove certain values that match on target.target from targetList?'
targetList.forEach(function(target, key) {
var os = getParameterByName('os');
if (os == "android") {
if (target.target.includes(":IOS")) {
targetList.splice(key, 1);
}
} else if (os == "ios") {
if (target.target.includes(":ANDROID")) {
targetList.splice(key, 1);
}
}
if (target.target.includes(":IOS")) {
target.target = schools[target.target.replace(":IOS", "").toLowerCase()] + " (iOS)" || target.target;
}
if (target.target.includes(":ANDROID")) {
target.target = schools[target.target.replace(":ANDROID", "").toLowerCase()] + " (Android)" || target.target;
}
});
targetList contains an array like this:
[
{
"target": "t1",
"datapoints": [
[
51.0,
1483574400.0
],
[
54.0,
1485561600.0
],
[
54.0,
1485648000.0
]
]
},
{
"target": "t2",
"datapoints": [
[
56.0,
1484265600.0
],
[
70.0,
1484352000.0
],
[
71.0,
1484438400.0
],
[
51.0,
1484611200.0
]
]
},
]
What I'm attempting to do is that where a target matches certain criteria .includes() I want to remove the entire containing object/array.
It seems to me your code works just fine. I've created a snippet where I removed the extra processing, to show that what you have already does what you ask.
Is there a reason you're doing stuff to target.target once you've removed it from the array? Do you have a reference to the containing object somewhere else?
var targetList = [
{
"target": "t1",
"datapoints": [
[
51.0,
1483574400.0
],
[
54.0,
1485561600.0
],
[
54.0,
1485648000.0
]
]
},
{
"target": "t2",
"datapoints": [
[
56.0,
1484265600.0
],
[
70.0,
1484352000.0
],
[
71.0,
1484438400.0
],
[
51.0,
1484611200.0
]
]
},
];
targetList.forEach(function(target, key) {
if (target.target.includes("t2")) {
targetList.splice(key, 1);
}
});
console.log(targetList);

Categories

Resources