I am receiving a JSON object from the backend now I just want "result" array only in my template variable in my angular application from it.
{
"result":[
{"name":"Sunil Sahu",
"mobile":"1234567890",
"email":"abc#gmail.com",
"location":"Mumbai",
"Age":"19"
}
],
"status":200
}
Try with
variable_name["result"].
Try with
var data = response from the backend
var result = data.result;
$var = '{"result":[{"name":"Sunil Sahu","mobile":"1234567890","email":"abc#gmail.com","location":"Mumbai","Age":"19"}],"stats":200}';
If your $var is string, you need to turn it to "array" or "object" by json_decode() function
object:
$var_object = json_decode($var); //this will get an object
$result = $var_object->result; //$result is what you want to get
array:
$var_array = json_decode($var, true); //this will get an array
$result = $var_array['result']; //$result is what you want to get
Else if $var is object, direct use
$result = $var->result; //$result is what you want to get
As result is an array of objects, you can either use any loop to extract key value pair or you can directly access the array using index value.
var results = data["result"] // this would return an array
angular.forEach(results, function(value, key) {
//access key value pair
});
For accessing results in HTML, ng-repeat directive can be used.
Your question didn't explain further, but in the simple way try this :
const stringJson = `{
"result":[
{"name":"Sunil Sahu",
"mobile":"1234567890",
"email":"abc#gmail.com",
"location":"Mumbai",
"Age":"19"
}
],
"status":200
}`
const obJson = JSON.parse(stringJson);
console.log(obJson.result);
Related
I need some help,
I've got a json with some parameters inside of it, actually 2 but one day we may add some more in it.
I want to find between some object in an array the right one thanks to all parameters in the json
Am i using the right method ?
to be clearer, i want the param.t to match with the element.t, and the param.tid to match with the element.tid and if moving forward one more parameter cd1 is added to the JSON, this param.cd1 will match with element.cd1
thanks for the time !
const array1 = [{"t":"pageview","de":"UTF-8","tid":"UA-xxxxxxxxxx-17","cd1":"Without cookie"},{"t":"timing","de":"UTF-8","tid":"UA-xxxxxxxx-1","cd1":"France"}];
const param = { t: 'pageview', tid: 'UA-xxxxxxxxxx-17' }
for (let [key, value] of Object.entries(param)) {
console.log(`${key}: ${value}`);
}
const obj = array1.find(element => element.t == param.t);
If I am following correctly, you want to compare an array of objects to an object and based on some keys in 'param' object you want to filter out your array1.
const array2 = [{"t":"pageview","de":"UTF-8","tid":"UA-xxxxxxxxxx-17","cd1":"Without cookie"},{"t":"timing","de":"UTF-8","tid":"UA-xxxxxxxx-1","cd1":"France"}];
const param1 = { t: 'pageview', tid: 'UA-xxxxxxxxxx-17' }
const test = array2.find(checkExist);
const checkExist = el => {
return el.t == param1.t && el.tid == param1.tid; // here you can add your keys in future
}
I have two json arrays like
var json1 = [{"city":"Ahmedabad"}]
var json2 = [{"State":"Gujarat"}]
I want them merge in to single arrays
var finalObj = [{"city":"Ahmedabad","State":"Gujarat"}]
If you are using concat() method then the arrays will get merged not the elements then you will get an output somewhat like
[{"city":"Ahmedabad"},{"State":"Gujarat"}]
If you need an output like this,
[{"city":"Ahmedabad","State":"Gujarat"}]
then you can implement this,
var json1 = [{"city":"Ahmedabad"}];
var json2 = [{"State":"Gujarat"}];
function jsonConcat(destinationObj, sourceObj) {
for (var key in sourceObj) {
destinationObj[key] = sourceObj[key];
}
return destinationObj;
}
//since json1 & json2 are arrays you must mention index,
//here index is 0, because it's first json object
var finalObj = jsonConcat(json1[0], json2[0])
console.log(finalObj)
IMPORTANT - This function will replace if similar keys found in both arrays !
If two json arrays have the same length, like your example, each json object is a array what includes one object.
You can loop through each item of the json arrays, then merge all of them to a object, finally push it into a array - finalObj.
My way use Object Rest/Spread Properties, the feature available with es2018:
var json1 = [{ "city": "Ahmedabad" }]
var json2 = [{ "State": "Gujarat" }]
var finalObj = [];
for (let i = 0; i < json1.length; i++) {
finalObj.push({
...json1[i],
...json2[i]
})
}
console.log(finalObj);
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var finalObj = json1.concat(json2)
merge your array
use reduce to merge all the items into one object
wrap in array
var combinedObj = [...json1, ...json2].reduce((acc, obj) => {
return {
...acc,
...obj
}
}, {})
var combinedArr = [...combinedObj]
You can do merge by using spread / rest operators i.e ...
var json1 = [{"city":"Ahmedabad"}]
var json2 = [{"State":"Gujarat"}]
var result = [...json1, ...json2]; //this will merge them into one.
result will be new array as we have merge them into one.
You can also user concat method of Javascript. Please refer below for concat -
https://www.w3schools.com/jsref/jsref_concat_array.asp
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_concat
I'm trying to select certain keys from an JSON array, and filter the rest.
var json = JSON.stringify(body);
which is:
{
"FirstName":"foo",
"typeform_form_submits":{
"foo":true,
"bar":true,
"baz":true
},
"more keys": "foo",
"unwanted key": "foo"
}
Want I want:
{
"FirstName":"foo",
"typeform_form_submits":{
"foo":true,
"bar":true,
"baz":true
}
}
I've checked out How to filter JSON data in node.js?, but I'm looking to do this without any packages.
Now you can use Object.fromEntries like so:
Object.fromEntries(Object.entries(raw).filter(([key]) => wantedKeys.includes(key)))
You need to filter your obj before passing it to json stringify:
const rawJson = {
"FirstName":"foo",
"typeform_form_submits":{
"foo":true,
"bar":true,
"baz":true
},
"more keys": "foo",
"unwanted key": "foo"
};
// This array will serve as a whitelist to select keys you want to keep in rawJson
const filterArray = [
"FirstName",
"typeform_form_submits",
];
// this function filters source keys (one level deep) according to whitelist
function filterObj(source, whiteList) {
const res = {};
// iterate over each keys of source
Object.keys(source).forEach((key) => {
// if whiteList contains the current key, add this key to res
if (whiteList.indexOf(key) !== -1) {
res[key] = source[key];
}
});
return res;
}
// outputs the desired result
console.log(JSON.stringify(filterObj(rawJson, filterArray)));
var raw = {
"FirstName":"foo",
"typeform_form_submits":{
"foo":true,
"bar":true,
"baz":true
},
"more keys": "foo",
"unwanted key": "foo"
}
var wantedKeys =["FirstName","typeform_form_submits" ]
var opObj = {}
Object.keys(raw).forEach( key => {
if(wantedKeys.includes(key)){
opObj[key] = raw[key]
}
})
console.log(JSON.stringify(opObj))
I know this question was asked aways back, but I wanted to just toss out there, since nobody else did:
If you're bound and determined to do this with stringify, one of its less-well-known capabilities involves replacer, it's second parameter. For example:
// Creating a demo data set
let dataToReduce = {a:1, b:2, c:3, d:4, e:5};
console.log('Demo data:', dataToReduce);
// Providing an array to reduce the results down to only those specified.
let reducedData = JSON.stringify(dataToReduce, ['a','c','e']);
console.log('Using [reducer] as an array of IDs:', reducedData);
// Running a function against the key/value pairs to reduce the results down to those desired.
let processedData = JSON.stringify(dataToReduce, (key, value) => (value%2 === 0) ? undefined: value);
console.log('Using [reducer] as an operation on the values:', processedData);
// And, of course, restoring them back to their original object format:
console.log('Restoration of the results:', '\nreducedData:', JSON.parse(reducedData), '\nprocessedData:', JSON.parse(processedData));
In the above code snippet, the key value pairs are filtered using stringify exclusively:
In the first case, by providing an array of strings, representing the keys you wish to preserve (as you were requesting)
In the second, by running a function against the values, and dynamically determining those to keep (which you didn't request, but is part of the same property, and may help someone else)
In the third, their respective conversions back to JSON (using .parse()).
Now, I want to stress that I'm not advocating this as the appropriate method to reduce an object (though it will make a clean SHALLOW copy of said object, and is actually surprisingly performant), if only from an obscurity/readability standpoint, but it IS a totally-effective (and mainstream; that is: it's built into the language, not a hack) option/tool to add to the arsenal.
I'm using Node-Red and in node function I have:
...
res = dataTransform.transform();
//critic case: res = [{"pressure":null}];
key = Object.keys(res[0]);
if(res[0][[key]]!=null)
{
...
console.log("res: ", [key]+":"+res[0][[key]]);
}
on console.log I have always:
res: 0:[object Object]
And it enters in if-statement always (also when the "res[0][[key]]" is null).
What was I mistake?
Object.keys returns an array containing the keys of the Object. Your code is using that entire array rather than a value from within it.
In order to get to the value of pressure, you would use:
var keys = Object.keys(res[0]);
var key = keys[0];
if (res[0][key] != null) {
console.log(res[0][key]);
}
I need a dynamic variable in nodejs .
I use the allocine-api, and she return, a different object when I use it . For example :
allocine.api(type, {code: code}, function(error, result) {
if(error){
console.log('Error : '+ error);
return;
}
socket.emit("allocine_"+type ,result);
});
if type is "movie", result contain a movie object, but if type is "tvseries", result contain a tvseries object. So I need to take the variable "originalTitle" in "tvseries" or "movie" object, so I need to make this :
result.<type>.originalTitle
But, how to use the contain of "type" for this ?
I have try with the javascript method, and the use of "window['type']", but it's don't work in nodeJs .
as javascript objects elements can be accessed as an associative array ( cf mozilla js doc )
using myobject.myproperties is strictly equal to use myobject["myproperties"]
so if a var hold the properties name to read var myvar = "myproperties"; you could also use myobject[myvar]
so, concretely :
var o = {
tvseries : {
originalTitle : "hello world"
}
}, type = "tvseries";
console.log( o[type].originalTitle );
jsfiddle
also, if the result object get only one sub object, named by the type, you can get type name directly from it
var type = Object.keys( myobject )[0];
jsfiddle
or more simply :
var theTitle = myobject[ Object.keys( myobject )[0] ].originalTitle;
jsfiddle
var results = {};
results.a = {originalTitle: "One"};
var results2 = {b:{originalTitle: "Two"}};
console.log(results['a'].originalTitle); //now one
console.log(results2['b'].originalTitle); //now Two
With two ways of creating the object.
Try the fiddle:
http://jsfiddle.net/rmoskal/6rf0juq6/