Lodash findKey() method - javascript

As a part of a challenge I need to implement the .findKey() method myself. Below is the solution proposition, however, I get an error "predicate is not a function".
const _ = {
findKey(object, predicate) {
for (let key in object) {
let value = object[key];
let predicateReturnValue = predicate(value);
if (predicateReturnValue) {
return key;
};
};
undefined
return undefined;
}
};
Can anyone help?

function findKey(object, predicate) {
for (let key in object) {
let value = object[key];
let predicateReturnValue = predicate(value);
if (predicateReturnValue) { // just take the value
return key; // return key
}
}
}
const isEqual = a => b => a === b
const object = { a: 'Apple', b: 'Beer', c: 'Cake' }
alert(findKey(object, isEqual('Apple')));
alert(findKey(object, isEqual('Cakes')));

Related

Find if value is undefined of multiple keys in object

I would like to detect if some values are not defined in an object with several properties
for example :
let test = {
helo: undefined,
hey: "not undefined"
}
i tried this :
const object1 = {
a: 'somestring',
b: 42
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
but if possible, I don't want to use a for loop, I would like a boolean result in return
You could be looking for something like this.
const test = {
helo: undefined,
hey: "not undefined"
};
const some_undefined = Object.values(test).some(v => v === undefined);
console.log(some_undefined);
You can use a function for that :
const hasOneKeyUndefined = (object)=>
{
for (const [key, value] of Object.entries(object)) {
if (value === undefined) return true;
}
return false;
}
You could also use Object.keys
const test = {
helo: undefined,
hey: "not undefined"
};
Object.keys(test).map((key, idx) => test[key] === undefined)

How to get values from array of objects in javascript

I have an array of object from which I am trying to get values using map operator but I am getting the whole json objects all I want is just array of values.
Below is my code:
const obj = [
{
a: {
b: 'Paul',
}
},
{
c: 'Byeeee',
}
];
obj.map((val) => console.log(val));
what I am getting is
{ a: { b: 'Paul' } }
{ c: 'Byeeee' }
What I want is:
['Paul','Byeeee']
Someone let me know how can I get the desired output.
You can do this recursively. You can first start off by grabbing the values of your object, and then loop through those using .flatMap(). If you encounter a value that is an object, you can recursively grab the values of that object by recalling your function. Otherwise, you can return the value. The advantage of using .flatMap() here is that when the recursive call returns an array, we don't end up with inner arrays, but rather the array gets flattened into one resulting array:
const obj = [{ a: { b: 'Paul', } }, { c: 'Byeeee', } ];
const getValues = (obj) => {
return Object.values(obj).flatMap(val => Object(val) === val ? getValues(val) : val);
}
console.log(getValues(obj));
you can use the following solution.
const data = [{ a: { b: 'Paul' } }, { c: 'Byeeee' }];
const flatObjectValues = (obj, result) => {
// recursive function to get object values
const objValues = Object.values(obj);
if (objValues?.length > 0) {
objValues.map((v) => {
if (typeof v === 'object' && !Array.isArray(v)) {
flatObjectValues(v, result);
} else {
result.push(v);
}
return v;
});
}
};
const updatedData = [];
data.map((x) => flatObjectValues(x, updatedData));
console.log('updatedData: ', updatedData);
You can use recursion with array.reduce, like fellowing.
function getAllValues(objuct) {
return objuct.reduce((acc, curr) => {
if (typeof curr === 'object') {
return [...acc, ...getAllValues(Object.values(curr))];
}
return [...acc, curr];
}, []);
}
A recursive solution could be:
const arr = [{a: {b: "Paul",},},{c: "Byeeee",},];
const flatArrOfObjects = (arr) => {
const values = [];
for (const i in arr) flatObj(arr[i], values);
return values;
};
const flatObj = (obj, result) => {
for (const [key, value] of Object.entries(obj)) {
if (typeof value === "object") flatObj(value, result);
else result.push(value);
}
};
console.log(flatArrOfObjects(arr));

Access javascript object value by array

I have an object like: const obj = { 'abc': {'def': 1 } } and I have an array like const arr = ['abc', 'def'] How can I access obj.abc.def property of my object with the array?
Obviously, obj[arr] doesn't work, also obj[arr.join('.') doesn't work.
What I want to do is:
const obj = { 'abc': {'def': 1 } }
const arr = ['abc', 'def']
const value = obj[arr] // crash
// value should contain 1
You could take a dynamic approach and reduce the keys and take a default object, if a part is not accessable.
const
getValue = (object, keys) => keys.reduce((o, k) => (o || {})[k], object),
obj = { abc: { def: 1 } },
arr = ['abc', 'def'],
value = getValue(obj, arr);
console.log(value);
console.log(getValue(obj, ['foo', 'bar']));
The base is
const obj = { 'abc': {'def': 1 } }
const arr = ['abc', 'def']
console.log(obj[arr[0]][arr[1]]);
or if you need to do it with a function...
const obj = { 'abc': {'def': 1 } }
const arr = ['abc', 'def']
function access(obj, arr) {
return arr.reduce((o, key) => o[key], obj);
}
console.log(access(obj, arr));
const obj = { 'abc': {'def': 1 } }
const arr = ['abc', 'def']
var value = obj;
for(let key of arr){
value = value[key];
}
console.log(value);
You can access the array property by index only. so arr[0] will work.
const obj = { 'abc': {'def': 1 } }
const arr = ['abc', 'def']
const value = obj[arr[0]][arr[1]]
console.log(value)
or you can run the loop over it.
const obj = { 'abc': {'def' : {'ghi': 1 } } };
const arr = ['abc', 'def', 'ghi'];
let ans = null;
for (let i=0; i<arr.length; i++) {
if(i==0) {
ans = obj[arr[0]];
}
else {
ans = ans[arr[i]];
}
}
console.log(ans)
You can use Array#reduce for a dynamic array.
const obj = { 'abc': {'def': 1 } }
const arr = ['abc', 'def']
const res = arr.reduce((o,prop)=>o[prop], obj);
console.log(res);
If you do not want errors to be thrown on properties that do not exist, you can use the optional chaining operator.
const obj = { 'abc': {'def': 1 } }
const arr = ['abc', 'def', 'notdefined', 'notdefined2']
const res = arr.reduce((o,prop)=>o?.[prop], obj);
console.log(res);
What you try to do is somewhat called object value "get by path", some library have support this and for example ramda is a production-ready library for that, you should not try to reinvent the wheel (practice is okay)
In your context, ramda's path method could help you achieve to the case of arbitrary array of properties
const obj = {
'abc': {
'def': 1,
'ghi': {
'jkl': 10
}
}
}
console.log(R.path(['abc', 'def'], obj))
console.log(R.path(['abc', 'ghi'], obj))
console.log(R.path(['abc', 'ghi', 'jkl'], obj))
console.log(R.path(['abc', 'ghi', 'jkl', 'mno'], obj))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

Why my recursive function works only for one level?

I am trying to learn how to cope with the objects and arrays and I saw many ways of iterating objects but recursing doesn't work for me and I don't understand why. What am I doing wrong?
I need to loop through an object and just slightly change something in an array. In my case, it's uppercasing the keys
Here is what I've got for now
const development = {
port: 8080,
db: {
username: "jkdfs",
password: "dsfsdg",
name: "kslfjskd",
test: { test: 12, another: 'value' }
},
token_secret: "jfkjdsj",
hash_rounds: "kjsfkljdfkl"
};
function throughObject(obj) {
let collection = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
let value = obj[key];
if (typeof obj[key] !== 'object') {
collection[key.toUpperCase()] = value;
} else {
collection[key.toUpperCase()] = nestedObject(obj[key]);
}
}
function nestedObject(nested) {
const sub = {};
for (const k in nested) {
let v = nested[k];
if (typeof nested[k] !== 'object') {
sub[k.toUpperCase()] = v;
} else {
nestedObject(v);
}
}
return sub;
}
}
return collection;
}
const r = throughObject(development);
console.log(r);
When you're recursively calling the function on an object value, you still need to assign it to the sub object: sub[k.toUpperCase()] = nestedObject(v). Also, you don't need 2 different functions.
const development = {
port: 8080,
db: {
username: "jkdfs",
password: "dsfsdg",
name: "kslfjskd",
test: { test: 12, another: 'value' }
},
token_secret: "jfkjdsj",
hash_rounds: "kjsfkljdfkl"
};
function nestedObject(nested) {
const sub = {};
for (const k in nested) {
const v = nested[k];
if (typeof nested[k] !== 'object')
sub[k.toUpperCase()] = v;
else
sub[k.toUpperCase()] = nestedObject(v); // <- HERE
}
return sub;
}
console.log(nestedObject(development))
Here's a shorter version using Object.fromEntries()
const development={port:8080,db:{username:"jkdfs",password:"dsfsdg",name:"kslfjskd",test:{test:12,another:"value"}},token_secret:"jfkjdsj",hash_rounds:"kjsfkljdfkl"};
const convert = o =>
Object.fromEntries(
Object.entries(o).map(([k, v]) =>
[k.toUpperCase(), Object(v) === v ? convert(v) : v]
)
)
console.log(convert(development))

Create object with only defined properties

I have a function which returns an object with properties only which are defined.
How to refactor the function so that I don't need to make if clauses for every parameter value? There must be more elegant way to do this.
const getQuery = ({ foo, bar, zoo }) => {
const query = {};
if (foo) {
query.foo = foo;
}
if (bar) {
query.bar = bar;
}
if (zoo) {
query.zoo = zoo;
}
return query;
}
I would do something like
function getQuery(obj){
// filter the accepted keys
var filtered = Object.keys(obj).filter((k) => ~["foo", "bar", "baz"].indexOf(k))
// construct new object with filtered keys
var query = {}
filtered.forEach((k) => query[k] = obj[k])
return query
}
Here's a basic function that will copy only properties provided in the wantedProps array. It will not mutate the original object.
let filterProperties = (originalObject = {}, wantedProps = []) =>
{
let filteredObject = {};
wantedProps.forEach( val => filteredObject[val] = originalObject[val] );
return filteredObject;
}
If you're just trying to filter out undefined vals then you could do:
obj => {
let newObject = {}
Object.keys(obj).forEach(key => {
if(obj[key] !== undefined) newObject[key] = obj[key];
})
return newObject;
}

Categories

Resources