how to access a JSON object? [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
i have this JSON Object, and i wanna access to this > object.foda.forta.id or name.. in JAVASCRIPT
thanks
note: this json it's created by xml2js.Parser()
{
"object": {
"foda": [
{
"forta": [
{
"id": [
"1"
],
"name": [
"dasdghjg"
]
},
{
"id": [
"2"
],
"name": [
"jj"
]
},
{
"id": [
"3"
],
"name": [
"gjhjg"
]
}
]
}
]
}
}

You cant access by object.foda.forta.id
as foda and fotra are lists, you can access by object.foda[0].forta[0].id
Note - 0 is used for sample only you can use any index (less the size of array)

Your JSON was terribly created, lots of unnecessary Arrays, but you can access it like this:
var obj = {
"object": {
"foda": [
{
"forta": [
{
"id": ["1"],
"name": ["dasdghjg"]
},
{
"id": ["2"],
"name": ["jj"]
},
{
"id": ["3"],
"name": ["gjhjg"]
}
]
}
]
}
};
document.body.innerHTML = "ID: " + obj.object.foda[0].forta[0].id[0] + " - Name: " + obj.object.foda[0].forta[0].name[0];
Take a look at this fiddle!

Related

Javascript : How to remove object Item from nested Object Array? [duplicate]

This question already has answers here:
Filtering array of objects with arrays based on nested value
(8 answers)
Closed last month.
I need to remove one item from nested object array by filtering key value
sample json
[
{
"featureID": "e0152c71-657f-4bc2-b7f5-77e4d5a2a5a0",
"feature": "TestTwo",
"type": "TestTwo",
"rules": [
{
"ruleId": "89919182-feb1-402c-b9ad-03ae62586f84",
"ruleName": "Machine Guarding",
"featureName": "TestTwo",
"parameters": [
]
},
{
"ruleId": "e5361f7f-d8ae-424d-b781-a01987111181",
"ruleName": "Eye&Face Protection",
"featureName": "TestTwo",
"parameters": [
]
},
]
},
{
"featureID": "67d6e1bf-3919-4dcc-b636-236ab41d431b",
"feature": "TestThree",
"type": "TestThree",
"rules": [
{
"ruleId": "4e00e08e-6a34-47cf-9012-0800bc0063f2",
"ruleName": "Maximum People",
"featureName": "TestThree",
"parameters": [
]
},
{
"ruleId": "a9ab3ce2-e69c-4c0c-b561-1107baed1e68",
"ruleName": "Redzone",
"featureName": "TestThree",
"parameters": [
]
}
]
},
]
In above JSON, I need to remove an item from "rules" array by "ruleId" property.
i.e : remove "ruleName":"Machine Guarding" item by that ruleId property.
I tried below
deleteItems(argId){
this.done.find((items,d)=>items.feature == argID.featureName).rules.filter((int,ind)=>int.ruleId == argID.ruleId)
}
The above function passes the respective "ruleId" property.
const data=[{featureID:"e0152c71-657f-4bc2-b7f5-77e4d5a2a5a0",feature:"TestTwo",type:"TestTwo",rules:[{ruleId:"89919182-feb1-402c-b9ad-03ae62586f84",ruleName:"Machine Guarding",featureName:"TestTwo",parameters:[]},{ruleId:"e5361f7f-d8ae-424d-b781-a01987111181",ruleName:"Eye&Face Protection",featureName:"TestTwo",parameters:[]}]},{featureID:"67d6e1bf-3919-4dcc-b636-236ab41d431b",feature:"TestThree",type:"TestThree",rules:[{ruleId:"4e00e08e-6a34-47cf-9012-0800bc0063f2",ruleName:"Maximum People",featureName:"TestThree",parameters:[]},{ruleId:"a9ab3ce2-e69c-4c0c-b561-1107baed1e68",ruleName:"Redzone",featureName:"TestThree",parameters:[]}]}];
const deleteItems = (ruleIdToFilter) => {
return data.map((item) => {
item.rules = item.rules.filter((rule) => ruleIdToFilter != rule.ruleId);
return item;
});
};
let response = deleteItems("89919182-feb1-402c-b9ad-03ae62586f84");
console.log(response);

How to find the value nested inside an array of objects

Here I have to get value of file_info, I tried doing it using array.includes and array.find(), but got undefined.
My confusion here is related to, under 'facts', the first value is "==", then it has array of values associated to it. I could not figure out to find the values inside that nested object.
I even tried array.find(facts).contains(fileinfo) that did not work as well.
How can I solve this ??
"data": [
{
"task-id": "126e7267",
"type": "A",
"output": {...}
},
{
"task-id": "bdfddff3",
"type": "B",
"output": {
"id": "12b54370",
"facts": [
{
"==": [
"A",
{
"#type": "AA",
"#value": {
"id": "12b54370-4594-4033-a299-5480b593ee6d",
"facts": [
{
"==": [
"time",
1575759643.904254
]
},
{
"==": [
"mime",
"text/plain"
]
},
{
"==": [
"owner",
1000
]
},
{
"==": [
"size",
100
]
},
{
"==": [
"file_info",
"a0s5b2e6e739" // have to find and return this value
]
},
{
"==": [
"time",
{
"#value": "2019-12-07T23:01:50.703Z",
"#type": "timestamp"
}
]
},
],
}
}
]
},
....
]
}
},
{
"task-id": "5f557eac",
"type": "C",
....
},
],
I have tried to validate your json string. It seems to be invalid. For answering this question , i would assume below string to be your json :
{"data":[{"task-id":"126e7267","type":"A","output":{}},{"task-id":"bdfddff3","type":"B","output":{"id":"12b54370","facts":[{"==":["A",{"#type":"AA","#value":{"id":"12b54370-4594-4033-a299-5480b593ee6d","facts":[{"==":[{"time":{"#value":"1575759643.904254"}}]},{"==":["mime","text/plain"]},{"==":["owner",1000]},{"==":["size",100]},{"==":[{"file_info":"a0s5b2e6e739"}]},{"==":["time",{"#value":"2019-12-07T23:01:50.703Z","#type":"timestamp"}]}]}}]}]}},{"task-id":"5f557eac","type":"C"}]}
I had tried to figure out a repetative pattern in your json but since "#value" tag is seen inside only one "facts" object below code should help you getting started . For given json , below code prints the value of "file_info"(Here , i'am assuming that "file_info" should be followed by a colon(:) i.e. "a0s5b2e6e739" is the value you are looking for) :
var jsonStr = '{"data":[{"task-id":"126e7267","type":"A","output":{}},{"task-id":"bdfddff3","type":"B","output":{"id":"12b54370","facts":[{"==":["A",{"#type":"AA","#value":{"id":"12b54370-4594-4033-a299-5480b593ee6d","facts":[{"==":[{"time":{"#value":"1575759643.904254"}}]},{"==":["mime","text/plain"]},{"==":["owner",1000]},{"==":["size",100]},{"==":[{"file_info":"a0s5b2e6e739"}]},{"==":["time",{"#value":"2019-12-07T23:01:50.703Z","#type":"timestamp"}]}]}}]}]}},{"task-id":"5f557eac","type":"C"}]}';
var jsonObj = JSON.parse(jsonStr);
//If there is a repetative pattern , you can replace this hard coding with your pattern.
var objArray = jsonObj["data"][1]["output"]["facts"][0]["=="][1]["#value"]["facts"];
console.log(objArray);
if(objArray && objArray.length >0){
for(let i =0;i<objArray.length;i++){
if(objArray[i] && objArray[i]["=="] && objArray[i]["=="].length > 0 && objArray[i]["=="][0]["file_info"]){
//here "file_info" is fetched
console.log('here ',objArray[i]["=="][0]["file_info"]);
}
}
}
Hope above code helps you to get started.
You can map and filter the object/array to get the result if the format is fixed. Here, I am writing to a Map and retrieving the property I need at the very end.
let data = [
{
"task-id": "126e7267",
"type": "A",
"output": {}
},
{
"task-id": "bdfddff3",
"type": "B",
"output": {
"id": "12b54370",
"facts": [
{
"==": [
"A",
{
"#type": "AA",
"#value": {
"id": "12b54370-4594-4033-a299-5480b593ee6d",
"facts": [
{
"==": [
"time",
1575759643.904254
]
},
{
"==": [
"mime",
"text/plain"
]
},
{
"==": [
"owner",
1000
]
},
{
"==": [
"size",
100
]
},
{
"==": [
"file_info",
"a0s5b2e6e739" // have to find and return this value
]
},
{
"==": [
"time",
{
"#value": "2019-12-07T23:01:50.703Z",
"#type": "timestamp"
}
]
},
],
}
}
]
}
]
}
},
{
"task-id": "5f557eac",
"type": "C",
"output": {}
}
]
const map = new Map()
const facts = data
.map(d => d.output)
.filter(o => o.hasOwnProperty('facts'))
.map(d => d.facts)
.map(i => i[0]["=="][1])
.map(d => d["#value"].facts)
const item = facts.forEach(o => o.forEach(i => map.set(i["=="][0], i["=="][1])))
console.log(map.get("file_info"))

Data Manipulation of json encoded string [duplicate]

This question already has answers here:
Pivot or Transforming JavaScript object
(2 answers)
Closed 3 years ago.
I have the following JSON encoded string that I would like to manipulate using javascript such that the x and y axis values are combined into a two dimensional array names values.
[
{
"key": "0",
"xaxis": "1492041600000",
"yaxis": "512"
},
{
"key": "0",
"xaxis": "1492045200000",
"yaxis": "985"
},
{
"key": "1",
"xaxis": "1492048800000",
"yaxis": "685"
},
{
"key": "1",
"xaxis": "1492052400000",
"yaxis": "935"
}
]
I needs to render as:
[
{
"key": "0",
"values": [
[1492041600000, 512],
[1492045200000, 985]
]
},
{
"key": "1",
"values": [
[1492048800000, 685],
[1492052400000, 935]
]
}
]
Can someone please show me how to perform this data manipulation?
Thank you!
Using map-reduce, you should be able to get the behavior you want.
const results = [{"key":"0","xaxis":"1492041600000","yaxis":"512"},{"key":"0","xaxis":"1492045200000","yaxis":"985"},{"key":"1","xaxis":"1492048800000","yaxis":"685"},{"key":"1","xaxis":"1492052400000","yaxis":"935"}]
const reducedResults = results.reduce((acc, result) => {
if(acc[result.key]) {
acc[result.key].values.push([result.xaxis, result.yaxis]);
} else {
acc[result.key] = { key: result.key, values: [[result.xaxis, result.yaxis]] }
}
return acc;
}, {});
const newResults = Object.values(reducedResults);
console.log(newResults);

How to convert object into array with lodash

I have below object
{
"holdings": [
{
"label": "International",
"value": 6
},
{
"label": "Federal",
"value": 4
},
{
"label": "Provincial",
"value": 7
}
]
}
I want to convert it into below object with lodash
{
"holdings": [
[
"International",
6
],
[
"Federal",
4
],
[
"Provincial",
7
],
[
"Corporate",
7
]
]
}
is there any way to change it. Please suggest.
If you want to use only lodash, then you can do it with _.mapValues and _.values to get the result, like this
console.log(_.mapValues(data, _.partial(_.map, _, _.values)));
// { holdings: [ [ 'International', 6 ], [ 'Federal', 4 ], [ 'Provincial', 7 ] ] }
The same can be written without the partial function, like this
console.log(_.mapValues(data, function(currentArray) {
return _.map(currentArray, _.values)
}));
// { holdings: [ [ 'International', 6 ], [ 'Federal', 4 ], [ 'Provincial', 7 ] ] }
This works recursively (So has to be called on the holdings property if you want to keep that) and "understands" nested objects and nested arrays. (vanilla JS):
var source = {
"holdings": [
{
"label": "International",
"value": 6
},
{
"label": "Federal",
"value": 4
},
{
"label": "Provincial",
"value": 7
}
]
}
function ObjToArray(obj) {
var arr = obj instanceof Array;
return (arr ? obj : Object.keys(obj)).map(function(i) {
var val = arr ? i : obj[i];
if(typeof val === 'object')
return ObjToArray(val);
else
return val;
});
}
alert(JSON.stringify(ObjToArray(source.holdings, ' ')));

Fetching the JSON value [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I need to fetch the values from this JSON in my java script:
[{
"selectionName": "Select",
"subSelections": [{
"id": 4,
"subSelectionName": "Select",
"description": "Deepmala"
}
]
}, {
"selectionName": "week14",
"subSelections": [{
"id": 7,
"subSelectionName": "1",
"description": ""
}
]
}, {
"selectionName": "test",
"subSelections": [{
"id": 6,
"subSelectionName": "test",
"description": ""
}
]
}, {
"selectionName": "select",
"subSelections": [{
"id": 3,
"subSelectionName": "sub-select",
"description": "Created by Prakash"
}
]
}, {
"selectionName": "testcreate",
"subSelections": [{
"id": 1,
"subSelectionName": "testcreate",
"description": ""
}
]
}, {
"selectionName": "by htmlwidget",
"subSelections": [{
"id": 5,
"subSelectionName": "by htmlwidget",
"description": "created by html widget"
}
]
}
]
Any suggestions?
You could use something like JSONSelect to extract certain values.
http://jsonselect.org/
Here's an example of how to use it:
(found in this JSFiddle)
$(function(){
/*
Json as easy as SQL ??? RT #lloydhilaiel JSONSelect - CSS-like selectors for JSON - http://jsonselect.org
Testing...
*/
var jsonData = {
"name": {
"first": "Lloyd",
"last": "Hilaiel"
},
"favoriteColor": "yellow",
"languagesSpoken": [
{
"language": "Bulgarian",
"level": 2},
{
"language": "English",
"level": 1},
{
"language": "Spanish",
"level": 7}
]
};
var selector = '.name > *'; // xPath CSS like selector
try {
var resultObj = JSONSelect.match(selector, jsonData);
console.log(typeof resultObj);
console.log(resultObj);
console.log('- - - - -');
JSONSelect.forEach(selector, jsonData, function(resultObj) {
console.log(typeof resultObj);
console.log(resultObj);
console.log('- - - - -');
$('body').append('<p>' + $.trim(JSON.stringify(resultObj, null, ' ')) + '</p>');
});
} catch(e) { console.log(e); }
});
JSON objects are easy to handle
var JSON = //Your JSON Object
JSON[0].selectName //returns 'Select'
JSON[0].subSelections[0].id //returns 4
and so on.
Any array objects can be treated as arrays. Any mapped objects can be returned by using the key like a field name for the JSON object.

Categories