I am using javascript array.find on my list of object arrays. I want to get another property of that object only when compared to that
property is available.
When compared to t, I get value as 'Value1'
When compared to t1, I get undefined. I want to check for 'undefined' and get the value only when available.
const t = 'abc';
const t1= 'xyz';
temp = [ {key: "abc", value: "Value1}]
temp.find( check => check.key === t ).value);
Depending on how you intend to use the value, you will likely find you need some type of value as a result of your search. This will allow you to substitute something or nothing as needed.
const t = 'abc';
const t1= 'xyz';
temp = [ {key: "abc", value: "Value1"}]
const result = temp.find( check => check.key === t1 ) || {value:'Not Found!'};
console.log(result.value);
Firstly, you were missing a closing quote. Secondly, use some and find:
const t = 'abc';
const t1= 'xyz';
const temp = [{key: "abc", value: "Value1"}];
if (temp.some(({ key }) => key == t)) console.log(temp.find(({ key }) => key == t).value);
If you want it to throw an error, return undefined, return a default or something else, you can check for undefined like so:
x = list.find(logic)
if(x){
//carry on as normal
else{
//handle it not being found
}
Related
I am trying to get the value associated with a key and create a new object, such as below. However when I assign the value of employeeCountryName to the object newCountryList, i get employeeCountryName returned and not "United Kingdom".
Any thoughts why this may be?
const countryList = {
"United Kingdom": "GBR"
};
const employeeCountryCode = "GBP"
const getKey = (obj, val) => Object.keys(obj).find(key => obj[key] === val);
const employeeCountryName = getKey(countryList, employeeCountryCode);
const newCountryList = {
employeeCountryName: employeeCountryCode
};
Keep in mind that when you define an object, it's keys aren't based on any other variables by default, they are just strings taken as keys. In order to tell javascript to take the value of a variable you have predefined instead of using it directly as a key, you need to add [] around them like this:
const variableName = 'keyToUse';
const object = { [variableName]: 1 } // { keyToUse: 1 }
You can use like that;
const newCountryList = {
[employeeCountryName]: employeeCountryCode
};
By the way, in your case find function couldn't find any key-value pair so it returns undefined. Because "United Kingdom" field has a GBR value and you're trying to find GBP
I have a data response that responds with different objects in an array.
I have tried a variety of different methods to determine if the key 'name' exists including:
const hasName = array.forEach(item => "name" in item )
const hasName = array.forEach(item => Object.keys(item).includes('name') )
const hasName = array[0].hasOwnProperty("name") ? true : null
const hasName = array => array.some(x => x.some(({ name }) => name));
// lodash 'has' method
const hasName = has(array, 'name')
Array1 returns objects like:
[
{
name: 'cool name'
}
]
Array2 returns objects like:
[
{
group: 'cool group'
}
]
All of the methods I tried have either returned undefined or nothing at all and I'm completely at a loss for why. I have scoured Stack Overflow and the internet trying to get a better direction or an answer but I haven't been able to find anything.
You're not returning anything from some of your calls on the array. forEach for example runs a callback, and always returns undefined see docs. Your code just isn't working because you're using the functions incorrectly.
The code below filters your array to get the elements with a name property, then counts them to see whether one or more exists, which results in a true or false being stored in the hasName variable.
let myArr = [
{
name: 'cool name'
}
]
const hasName =
myArr
.filter(a => a.hasOwnProperty("name")) // filter for elements in the array which have a name property
.length // get the number of filtered elements
> 0 // check whether the number of elements in array with name prop is more than 0
console.log(hasName)
If you are sure that the "response" is fully received before the check, THEN
Your latest variant of the check can be implemented as follows:
array.some(obj => (obj.name !== undefined)); // fast, but not define .name if it is "undefined"
array.some(obj => obj.hasOwnProperty("name")); // slower, but will define .name with any value
Your solutions are generally correct, but it looks like you're a little confused,
Array.forEach always returns "undefined":
array.forEach(obj => {
console.log("name" in obj); // true for 1st array
console.log("group" in obj); // true for 2nd array
}); // return "undefined"
array[0].hasOwnProperty() works fine, and can't return "undefined" at all.
console.log(
array[0].hasOwnProperty("name") ? true : null; // return ("true" for the 1st array) AND ("null" for the 2nd)
);
When you used the Lodash, maybe you forgot to point to the object index?
_.has(array[0], 'name'); // return ("true" for the 1st array) AND ("false" for the 2nd)
Try a for loop
for (var i = 0; i < array.length; i++) {
if (array[i].hasOwnProperty('name')) {
console.log(array[i].name); //do something here.
break;
}
}
I have the following object with (always) 2 properties. It wil always have 2 properties. 3 properties won't be possible:
var people = {
'John': { ... },
'Peter': { ... }
}
And I have the variable var name = 'John'.
Is there a simple way to get the value of property 'Peter' when the value of name is 'John'?
Without hard-coding it with the names John en Peter. So the functionality must get the opposite property of the value in variable name
let name = 'John'; // or whatever
let names = Object.keys(people);
let otherName = names.find(n => n !== name);
people[otherName] // this gives you the value of the other name's property
Object.keys will give you an array of the property names.
filter lets you filter that array.
So:
const name = "John";
const people = {
'John': 1,
'Peter': 1
};
const [result] = Object.keys(people).filter(person => person !== name);
console.log({
result
});
I wrote a simple function, that does this. It takes a key, and an object. It returns the value of the element in the given object by the inverse key of the given key. This will only work if the object only has two keys.
var people = {
'John': { 'b':[3,4] },
'Peter': { 'a':[1,2] }
}
getInverseObjectElem = (key,object) => { // Define function 'getInverseObjectElem'
listOfObjectKeys = Object.keys(object) // Create an array of the object keys
inverseKey = listOfObjectKeys.filter(k => k != key)[0] // filter the list of keys, and get the first key that doesnt match the given key.
return object[inverseKey] // Return the value in the object, by the inverseKey
}
console.log(getInverseObjectElem('John',people))
You could try this:
for (let key in people){
if (key != name) return people[key];
}
I am making a SPA with Laravel(backend) and Vue.js. I have the following arrays:
accessArray:
["BIU","CEO","Finance","HRD","Group"]
access:
["BIU","Group"]
I want to compare the access array to the accessArray array and if there is a match to change the record (in the accessArray) and add a true value otherwise add a false value. I am doing this inside a Vue method.
... so far I got this:
var foo = ["BIU","CEO","Finance","HRD","Group"];
var bar = ["BIU","Group"];
$.each(bar, function (key, value) {
if ($.inArray(value, foo) != -1) {
var position = $.inArray(value, foo);
console.log(value + ' is in the array. In position ' + position);
foo[position] = {name: value, checked: true};
}
});
Which outputs this to the console:
BIU is in the array. In position 0
Group is in the array. In position 4
And this in Vue:
[
{"name":"BIU","checked":true},
"CEO",
"Finance",
"HRD",
{"name":"Group","checked":true}
]
The output I would like to achieve is the following:
[
{"name":"BIU","checked":true},
{"name":"CEO","checked":false},
{"name":"Finance","checked":false},
{"name":"HRD","checked":false},
{"name":"Group","checked":true}
]
Any help would be greatly appreciated, I have looked at many similar problems on SO but cant seem to find anything along these lines. I have also tried to add an else statement on the end but I (think) I'm converting it to an object so that doesn't seem to work.
Edit:
The data in foo comes from a Laravel config setting so is somewhat dynamic
The data in bar is JSON received from the Laravel ORM (its json stored in a text field)
An option with vanilla javascript:
var foo = ["BIU","CEO","Finance","HRD","Group"];
var bar = ["BIU","Group"];
var result = foo.map(name => {
var checked = bar.indexOf(name) !== -1
return { name, checked }
})
console.log(result)
You can use Array#map to iterate over the array and construct a new one, by checking if values are present in the other one through Array#includes
const accessArray = ["BIU","CEO","Finance","HRD","Group"];
const access = [ "BIU", "Group" ];
const result = accessArray.map( a => ({ name: a, checked: access.includes(a)}) ) ;
console.log(result);
A note: when using an arrow function and you want to return an object, you need to surround the object literal in () otherwise it would be interpreted as a code block.
Use reduce and inside the reduce call back check if the item is present in both accessArray & access . Create an object and the item present in both array set the value of checked to true or false
let arr1 = ["BIU", "CEO", "Finance", "HRD", "Group"]
let arr2 = ["BIU", "Group"];
let k = arr1.reduce(function(acc, curr) {
let obj = {}
if (arr2.includes(curr)) {
obj.name = curr;
obj.checked = true
} else {
obj.name = curr;
obj.checked = false
}
acc.push(obj);
return acc;
}, []);
console.log(k)
To achieve expected result use below option
1. Loop foo array
2.Remove initial if condition - "if ($.inArray(value, foo) != -1)" to loop through all
3. Do conditional check for checked - checked: $.inArray(value, bar) !== -1 ? true : false
codepen - https://codepen.io/nagasai/pen/GXbQOw?editors=1011
var foo = ["BIU","CEO","Finance","HRD","Group"];
var bar = ["BIU","Group"];
$.each(foo, function (key, value) {
foo[key] = {name: value, checked: $.inArray(value, bar) !== -1 ? true : false};
});
console.log(foo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Option 2:
Without using jquery and using simple forEach to loop through foo
codepen - https://codepen.io/nagasai/pen/YOoaNb
var foo = ["BIU","CEO","Finance","HRD","Group"];
var bar = ["BIU","Group"];
foo.forEach((v,i) => foo[i] = {name: v , checked : bar.includes(v)})
console.log(foo);
Trying to check on the result of linq.js FirstOrDefault(), but checking for null or undefined isn't working. Having some trouble debugging it, but I can see that it is returning some sort of object.
There isn't any documentation for this method online that I could find.
I've tried:
var value = Enumerable.From(stuff).FirstOrDefault('x => x.Name == "Doesnt exist"')
if (value) {
alert("Should be not found, but still fires");
}
if (value != null)
alert("Should be not found, but still fires");
}
The signatures for the FirstOrDefault() function is:
// Overload:function(defaultValue)
// Overload:function(defaultValue,predicate)
The first parameter is always the default value to return if the collection is empty. The second parameter is the predicate to search for. Your use of the method is wrong, your query should be written as:
var value = Enumerable.From(stuff)
.FirstOrDefault(null, "$.Name === 'Doesnt exist'");
We figured out the answer as I was typing this out. Since there is so little documentation, I'll share.
You need to move the lambda into a Where clause before the FirstOrDefault().
When
var someArray = ["Foo", "Bar"];
var result = Enumerable.From(someArray).Where('x => x == "Doesnt exist"').FirstOrDefault();
Result is undefined (correct)
When
var someArray = ["Foo", "Bar"];
var result = Enumerable.From(someArray).Where('x => x == "Bar"').FirstOrDefault();
Result is 'Bar' (correct)
When
var someArray = ["Foo", "Bar"];
var result = Enumerable.From(someArray).FirstOrDefault('x => x == "Bar"');
Result is 'Foo' (incorrect)