Get elements inside javascript object that shares similar property names - javascript

I want to know if there is a way to extract / search the elements which contain similar property from a javascript object.
Just to be more specific, If I have the following object:
Live Demo: http://jsfiddle.net/oscarj24/sMWUL/
var enrolled = {};
enrolled['enrolled/ruby/S1234'] = {
course: {
id: 'P01',
desc: 'Ruby course'
},
student: {
id: 'S1234',
name: 'John Doe'
}
};
enrolled['enrolled/php/S1234'] = {
course: {
id: 'P02',
desc: 'PHP course'
},
student: {
id: 'S1234',
name: 'Foo Bar'
}
};
enrolled['enrolled/java/S6666'] = {
course: {
id: 'P03',
desc: 'Java course'
},
student: {
id: 'S6666',
name: 'Bill Gates'
}
};
Then I'll have some similar properties inside the enrolled object (like the ones sharing the S1234 string at the end).
So, my question is:
How can I extract the elements with string similarities or coincidences in the properties?
I've looked that javascript objects are very limited and the only thing I can do to check if a property exists or not is: obj.hasOwnProperty(prop) (but this is not what I am looking for). Is there a way to use regex to check for this? (just saying, seems not to be possible).
Just to know, I am using ExtJS 4.2 but I can't find something to achieve what I need in the API documentation (correct me if wrong).

You can use a for each loop to see if what you're searching for is in the string.`
for (key in enrolled)
{
if(key.indexOf('S1234') > -1)
{
console.log(key);
//Perform your actions here
}
}
Fiddle here: http://jsfiddle.net/brettwlutz/sMWUL/2/

how about this?
for(var prop in enrolled){
console.log(prop);
//check if prop matches string regex.
}

Related

find property inside nested array javascript

I have an object that contains data to display information pulled from the Notion API. I can see the data but not sure how I can extract nested array inside the current array. My goal is to use the category property to create a filter but first I need to get the string to create the condition.
Here is what the data looks like currently. How would I go about to filter out name: "commissions":
resultsArray:
0:
properties
category:
id: "sdasd"
multi_select:
0:
id:"324234"
name: "commissions"
I have tried use find but it doesn't do what I expect. My suspicion is that I will have to loop over the nested array again.
You can use find inside find condition
like this :
data.resultsArray.find(item=>item.category.multi_select.find(select=> select.name === "commissions"))
const data = {
resultsArray: [
{
category: {
id: 'sdasd',
multi_select: [
{
id: '324234',
name: 'commissions',
},
],
},
},
],
};
const result = data.resultsArray.find(item=>item.category.multi_select.find(select=> select.name === "commissions"))
console.log(result)

Map property of an object of object trimming the name property if its too long

Given an object like this:
var fullObj = {
prop1: "myProp1",
subobject: {
Obj1_id: {
id: "Obj3_id",
name: "./",
otherProperties:...
},
Obj2_id: {
id: "Obj2_id",
name: "Obj2_id",
...
},
Obj3_id: {
id: "Obj3_id",
name: "Obj3",
....
},
I would like to trim the name if it is too long(more than myLength) plus 3 dots
I know like to use something like that otherwise just the name
name=name.substr(0,myLength)+"..."
Given that this object is in a react state how can I manipulate the state (using class based component)?
I hope this is what you were looking for. It will check if the value of name is greater then 3 then it will take the first 3 letters from the name and add ... in it.
Object.keys(fullObj.subobject).forEach(function(key) {
if(fullObj.subobject[key].name.length > 3){
fullObj.subobject[key].name = fullObj.subobject[key].name.slice(0,3) + "..."
}
});

Make a new JS Object using an old one, see description for example

This one is pretty straight forward, I think I just don't know what tool to use. I've got an object which looks like this:
{
email: "email#aol.com", phone: "222-333-4444"
}
i am looking to convert it to the following array with nested objects
[
{
name: "email", value: "email#aol.com"
},
{
name: "phone", value: "222-333-4444"
},
]
im familiar with .map() and Oject.keys, just keep running into a wall on this one.
this is what i've been trying but im getting syntax errors
const data = Object.keys(data).map(key => {name: key, value: data[key]});
can anyone help? hopefully some quick points for someone. thanks!
To return object from arrow function, you must wrap it in () doc
To return an object literal expression requires parentheses around expression
const data = {
email: "email#aol.com", phone: "222-333-4444"
};
const result = Object.keys(data).map(key => ({name: key, value: data[key]}));

template literals giving different answer

I'am javascript beginner trying to code to improve myself, at the moment trying to learn 'template literals' and for some reason getting different answer by putting inside 'template literals'. Here is my code :
const foodArray = [
{ name: 'Burrito' },
{ name: 'Pizza' },
{ name: 'Burger' },
{ name: 'Pasta' }
];
for (let i = 0; i < foodArray.length; i++) {
console.log(`i value: ${i} | Food Name:`, foodArray[i]);
}
<p id="demo"></p>
so now i'm putting 'foodArray[i]' inside 'template literals' like this ' ${foodArray[i] ' but it is giving me '[object Object]', shouldn't it give same result ? maybe i'm doing something wrong here
const foodArray = [
{ name: 'Burrito' },
{ name: 'Pizza' },
{ name: 'Burger' },
{ name: 'Pasta' }
];
for (let i = 0; i < foodArray.length; i++) {
console.log(`i value: ${i} | Food Name: ${foodArray[i]}`);
}
<p id="demo"></p>
console.log is going to do things differently than the template literal. the console.log will send the actual object reference to the console client and the particular console client will decide from there how to present that object, they all do it slightly differently. template literals will always call the objects .toString() method. some console clients just call the .toString() method as well, some use JSON.stringify, some use sophisticated object explorers, the SO console client uses some method to produce "pretty" JSON.
you can get it closer to the console representation or at least make it consistent by using JSON.stringify:
console.log(`i value: ${i} | Food Name: ${JSON.stringify(foodArray[i])}`);
but generally, in real world programming, you won't be sending objects to a template literal, so this isn't a huge concern in most applications.

How to find values from another JSON object

I have set of json objects.
Languages
User Details
User Details have the languages field - which have more than 1 values.
Here is my sample json
$scope.languages = [
{id: 1, text: 'English'},
{id: 2, text: 'French'},
{id: 3, text: 'Hindi'},
{id: 4, text: 'Telugu'}
];
$scope.users = [{name: 'first user', status: 1,language:"1"},
{name: 'second user', status: 2,language:"1,2"},
{name: 'third user', status: 3,language:"1,3,4"}];
In my view i want to list the user name and languages.
<li ng-repeat="user in users">{{user.name}} - {{testString}}</li>
I know to do for single value. But for multiple values. I have the logic but i don't know how to implement. I am thinking that. First i have to split the user language string and change into array and then find the index of the language id and then return the language text.
I have the code to return language name from ID.
var foundItem = $filter('filter')($scope.languages, { id: 3 }, true)[0];
var index = $scope.languages.indexOf(foundItem );
$scope.result = $scope.languages[index].text;
So now the problem is how to print the languages next to the user name?
I tried like this
$scope.testString = function() {
return "return test string";
}
{{testString}}
But its not working. If this works we can pass the langugae codes as parameter and i can add the search code inside the testString function.
Thanks
testString is a function so you cannot use it like {{testString}}, you have to call that function {{testString()}}
You can simplify your code like this.
$scope.getLanguages = function (langs) {
var l = [];
angular.forEach(langs.split(','), function (lang) {
l.push(findLanguageTextById(parseInt(lang)));
})
return l.join(', ');
}
function findLanguageTextById (langId) {
for(var i = 0;i<$scope.languages.length;i++) {
if ($scope.languages[i].id == langId) {
return $scope.languages[i].text;
}
}
}
I have created a working demo for your problem take a look.
http://plnkr.co/edit/Cdl8y58IExoVSZV6lp76?p=preview
I think you are not calling the function,
$scope.testString = (function() {
return "return test string";
})();

Categories