How to do this: obj[i].["name of thing in object"] - javascript

I tried to work it out and ask who I could but no one gave me an answer that would work. can anyone advise me?
obj[i].["name of thing in object"]
this is array:
[
{
"name": "DISBOARD#2760",
"id": "3020508723832240"
},
{
"name": "Gumernus#0122",
"id": "7814540349956106"
}
]

Assuming your object looks a bit like
let obj = [
{ nameOfThingInObject: 'first'},
{ nameOfThingInObject: 'second'}
];
To retrieve the nameOfThingInObject you can do two things:
Use . to access the property
Use [] to access the property
Your example in the question seems to try both, which will result in an error. To retrieve the value, you can thus do:
let firstMethod = obj[0].nameOfThingInObject;
let secondMethod = obj[0]['nameOfThingInObject'];

Related

Find specific JSON key and return its value in Javascript

I have some JSON from an API which I am logging in the console.
This is easy for something like the id where I can do this...
let movieID = out.id;
console.log(movieID)
But how can I also return the 'name' of the person whose job is specifically 'Director' from JSON example like this? Basically I need to do something like 'if someone has the JOB of DIRECTOR, log their name to the console.
{
"id": 37291,
"credits": {
"crew": [
{
"name": "John Smith",
"job": "Producer"
},
{
"name": "Mary Jones",
"job": "Director"
}
]
}
}
You can get the list of the crew, like you described above. Then find the first entry in that list where the job equals "Director" and put it in a variable:
let director = out.credits.crew.find(member => member.job == "Director");
You can then log the data, as you did for the movie itself.
Something like this would do literally what you asked which was to console log out the names
credits.crew.foreach((crewMember) => {
if (crewMember.job == 'Director') {
console.log(crewMember.name)
}
})
Use underscore:
_.filter(credits.crew, (key) => key.job === 'Director')
That will give you all the keys with that value. Trust me you should use underscore or lodash because objects can get super tricky and it saves you a ton of time.

Filter Array Using Partial String Match in Javascript

I have an array of objects where the value I need to filter on is buried in a long string. Array looks like:
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
},
So if I wanted to grab all the partnerId objects where value includes parent_sku how would I do that?
console.log(data.value.includes('parent_sku') returns cannot read property 'includes' of null.
EDIT:
Didn't think this mattered, but judging by responses, seems it does. Here's the full response object:
Response body: {
"data": {
"configurationByCode": [
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
}
I'm passing that into a re-usable function for filtering arrays:
const parentSkuPartners = filterArray(res.body.data.configurationByCode, 'parent_sku');
Function:
function filterArray(array, filterList) {
const newList = [];
for (let i = 0; i < array.length; i += 1) {
console.log('LOG', array[i].data.value.includes('parent_sku');
}
}
The problem is somewhere else. The code you've tried should work to find if a value contains a string – I've added it the snippet below and you'll see it works.
The issue is how you are accessing data and data.value. The error message clearly states that it believes that data.value is null. We would need to see the code around it to be able to figure out what the problem is. Try just logging to console the value of data before you run the includes function.
const data = {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}", "partnerId": 1
};
console.log('includes?', data.value.includes('parent_sku'));
You can use data.value.includes('parent_sku') as you have suggested. The issue here is that your object is nested inside an unnamed object.
try:
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
The problem was some of the values for value were null. Adding an extra conditional fixed it:
if (array[i].data.value !== null) {
Use lodash includes, and lodash filter like
let configurationByCode = [{
data: {
value: {
cols:["parent_sku"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 1
}
}, {
data: {
value: {
cols:["nothing"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 2
}
}];
let wantedData = _.filter(configurationByCode, (config) => {
return _.includes(config.data.value.cols, 'parent_sku');
});
console.log( wantedData );
https://jsfiddle.net/76cndsp2/

Getting values of json array in Mocha JS

I have following issue, this json is returned by api:
"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}
and I need to get names of all variables under products array, how to get them?
That values are constantly changing everyday, so I can not refer to their names
Trying console.log(res.body.menu.categories[i].products.values()); but its not worked.
Any sugesstion how can I get 10432471 and 10432481 from products? Without referring to variable names.
You are able to get that via Object.keys(res.body.menu.categories[i].products)
To get the object properties, the shortest is using Object.keys()
var obj = {"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}}
var properties = Object.keys(obj.products)
console.log(properties)

rule engine function inside Meteor bindEnvironment losing its this object

var process_request_rule = [
{
"name": "rule-name",
"condition": Meteor.bindEnvironment(function (R) {
R.when(this.request.type == 'some-type');
})
}];
In the above code, this.request was getting undefined as this was pointing to Meteor object not to the function object. After researching got to know that using arrow functions might resolve the issue. Tried using that as shown below.
var process_request_rule = [
{
"name": "rule-name",
"condition": Meteor.bindEnvironment((R) => {
R.when(this.request.type == 'some-type');
})
}];
Still no luck, Please help me binding this object
You can either drop using Meteor.bindEnvironment or just use second argument passed to condition callback — it is the same as supposed this. https://github.com/mithunsatheesh/node-rules/blob/master/lib/node-rules.js#L94
Something like this:
var process_request_rule = [
{
"name": "rule-name",
"condition": Meteor.bindEnvironment(function(R, session) {
R.when(session.request.type == 'some-type');
})
}];

Parsing a JSON object-within-an-object in javascript

I have a JSON object that looks like this:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [ {... // contains lots objects with the data I'd like to access } ]
As noted above, I want to access the product array of objects. I can't seem to do this though. I've tried:
console.log(json['cj-api']['products'][0]['product']);
But I get typeError: Cannot read property 'products' of undefined.
What's the correct way to access the array of product (note, singular product, not products). This data is coming from an external source so I can't alter the hyphen in cj-api.
EDIT: Here's what the raw console log of json looks like:
{"cj-api":{"products":[{"$":{"total-matched":"231746","records-returned":"999","page-number":"1"},"product":[{ << lots of data in here>>
EDIT 2: To further clarify, I got this object by running JSON.stringify(result) after I put some XML into XML2js.
i have tried the following JSON structure:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [
{
"a": "a",
"b": "b",
"c": "c"
}
]
}
]
}
};
with the log statement as:
console.log(json['cj-api']['products'][0]['product']);
And result is as follows:
[Object { a="a", b="b", c="c"}]
Well your way of accessing json is absolutely correct. This is for debugging. Try
console.log(json['cj-api']);
console.log(json['cj-api']['products']);
console.log(json['cj-api']['products'][0]);
console.log(json['cj-api']['products'][0]['product']);
Which ever line returns undefined means your json is broken there.
If this doesn't work then you need to check for other similar keys. Maybe they value you are trying to find is actually undefined.
Maybe you are trying to loop. If you are then check for the condition if (JSONStructure[key]==undefined) console.log("Undefined at position ..."). That is the only way if you have valid JSON.
typeError: Cannot read property 'products' of undefined means that json exists, but json['cj-api'] is undefined. If you are sure that you are using the right variable name, I think this might be a scope issue, where you are using an other variable than you intend to. json might be the json string, instead of the array-like object. Try renaming your variable and see if you still get this problem. Otherwise the string is not automatically parsed for you and you'll have to parse it with JSON.parse( ... ).
Edit:
var json = '{ "me": "be an evil string" }';
console.log( json ); //'{ "me": "be an evil string" }'
console.log( json['me'] ); //undefined
console.log( JSON.parse( json )['me'] ); // 'be an evil string'
Since your question is missing the last
}
]
}
}
and others here changed your example and made it work, did you try to correct it?
If not then I suggest you or the dataprovider correct the structure of the reply.
I have tried below json structure
var json={
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": []
}
]
}
}
now json['cj-api']['products'][0]['product'] will work

Categories

Resources