Get return Value from Object.keys - javascript

I have a function that searches an object, to see if a value exist in it but I can't get the value from it when I try to log it.
searchValue(object,value){
let valueExists = Object.keys(object).find(key => object[key].valueID === value );
console.log(valueExists);
}

You could use Object(o).values like :
let valueExists = Object.values(object).find(val => val === value )
console.log(valueExists)
JS Example :
function searchValue(object, value) {
let valueExists = Object.values(object).find(val => val == value)
console.log(valueExists)
}
let user = {
id: 12,
name: "aaa",
email: "aaaa#domain.com",
}
searchValue(user, "aaa")

If you already have value (as searchValue parameter) you don't need to "get" value because you already have it (below I simplify your implementation)
function searchValue(object, value) {
return Object.values(object).includes(value);
}
let obj = {a: "xx", b: "yy"};
let val = "yy"
if(searchValue(obj,val)) {
console.log("the object value exist and is:", val);
}
If you interest to find keys which are associated with value try this
function searchKeys(object, value) {
return Object.keys(object).filter(k=>object[k]==value);
}
let obj = {a: "xx", b: "yy", c:"xx"};
let val = "xx"
console.log("Keys contains 'xx' value:", searchKeys(obj,val));

To achieve expected result, use below option of using Object entries and looping with forEach for value
function searchValue(object,value){
Object.entries(object).forEach(v => {
if(v.indexOf(value) !== -1) console.log("valueExists")
});
}
let test = {
id : 11,
name: 'abc',
location: 'usa'
}
searchValue(test, 11)

Related

How to update Object in Array dynamically in React state

I'm fairly new to ReactJS and wrote this function I want to use to update an object in my state. It seems unable to use the "name" param to update my object and I don't really get why. I tried to code it in template literals as well.
const handleAccountingChange = (newValue, name, id) => {
const newState = selected.map((obj) => {
if (obj.id === id) {
return { ...obj, name: newValue };
}
return obj;
});
setSelected(newState);
};
I get no error in the browser console, but it doesn't update my state either. Any idea would be appreciated. I spent 2 hours on google but didn't find anything.
When you call obj.property = 'aaa' you set property to aaa.
What you try to do is update the property contained by the variable name, what you code does is update the property name.
To update a property from a variable you need to use :
const property = 'name'
obj[property] = 'aaa'
equivalente to :
obj.name == 'aaa'
This code solves your probleme :
const handleAccountingChange = (newValue, name, id) => {
// For the exemple I declare selected here
const selected = [ {id: 1, test: 'aaa'}, {id: 2, test: 'bbb'} ];
const newState = selected.map((obj) => {
if (obj.id === id) {
let myObj = {...obj};
myObj[name] = newValue;
return myObj;
}
return obj;
});
return newState; // instead ou can use setSelected(newState)
};
console.log(handleAccountingChange('ccc', 'test', 1));
const handleAccountingChange = (newValue, name, id) => {
const newState = selected.map((obj) => {
if (obj.id === id) {
return { obj[name]= newValue};
}
return obj;
});
setSelected({...newState});
}

Get the key of a JS Object from the value

I am trying to get the key of a JS Object in Typescript from an input value, the problem is that the values are inside an Array.
This is what I have seen in the case that the value is not in an array:
const exampleObject = {
key1: 'Geeks',
key2: 'Javascript'
};
function getKeyByValue(object, value) {
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
if (object[prop] === value)
return prop;
}
}
}
console.log(getKeyByValue(exampleObject,'Geeks')) // key1
This is an example of my object that I want to get the key from:
const exampleObject = {
key1: ['Geeks','test1','test2'],
key2: ['Javascript','test3','test4']
};
function getKeyByValue(object, value) {
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
if (object[prop] === value)
return prop;
}
}
}
console.log(getKeyByValue(exampleObject,'Geeks')) // undefined
I need to get the key without using Array.prototype.includes(), because typing the resulting variable as String gives me an error that it may be undefined.
My problem: I don't know how to go through the array inside the function to find the value and get the key
Update:
What I want is to avoid the possibility of returning an undefined, since the input value will always be inside the object, how can I achieve this?
#segmet
You can use my code
const exampleObject = {
key1: ['Geeks', 'test1', 'test2'],
key2: ['Javascript', 'test3', 'test4']
};
function getKeyByValue(object, value) {
var output = "";
for (var prop in object) {
// finding and removing element from array
object[prop].find(i => {
if (i === value) {
output = prop;
return prop;
}
}
)
}
return output
}
console.log(getKeyByValue(exampleObject, 'Geeks'))
You can achieve this with a single line of code by using 3 JavaScript methods - Object.keys(), Array.find() & Array.indexOf() :
const exampleObject = {
key1: ['Geeks','test1','test2'],
key2: ['Javascript','test3','test4']
};
function getKeyByValue(object, value) {
const res = Object.keys(exampleObject).find(key => exampleObject[key].indexOf(value) !== -1);
return res || ''
}
console.log(getKeyByValue(exampleObject,'Geeks'))
function getKeyByValue(object, value) {
const key = Object.entries(object).filter(([key, val]) => val.includes(value));
return Object.fromEntries(key);
}
Try this function instead
You will get the object matching your keys
You can do something like this and then check for null
const getKeyFromValue = (obj:Object, value:string | string[]) => {
for (let key in obj) {
if (typeof value === 'string') {
if (obj[ key ].includes(value)) {
return key;
}
}
else if (Array.isArray(value)) {
if (obj[ key ].every(val => value.includes(val))) {
return key;
}
}
}
return null;
}
One more try:
const exampleObject = {
key1: ['Geeks','test1','test2'],
key2: ['Javascript','test3','test4']
};
function getKeyByValue(obj, data) {
for (const [key, value] of Object.entries(obj)) {
return (~value.indexOf(data)) ? key : false
}
}
console.log(getKeyByValue(exampleObject,'Geeks'))

Update fields in nested objects in Typescript / Javascript

In Firestore you can update fields in nested objects by a dot notation (https://firebase.google.com/docs/firestore/manage-data/add-data?authuser=0#update_fields_in_nested_objects). I wonder how to make that work in Typescript / Javascript.
For example the following object:
const user = {
id: 1
details: {
name: 'Max',
street: 'Examplestreet 38',
email: {
address: 'max#example.com',
verified: true
}
},
token: {
custom: 'safghhattgaggsa',
public: 'fsavvsadgga'
}
}
How can I update this object with the following changes:
details.email.verified = false;
token.custom = 'kka';
I already found that Lodash has a set function:
_.set(user, 'details.email.verified', false);
Disadvantage: I have to do this for every change. Is their already a method to update the object with an object (like firestore did)?
const newUser = ANYFUNCTION(user, {
'details.email.verified': false,
'token.custom' = 'kka'
});
// OUTPUT for newUser would be
{
id: 1
details: {
name: 'Max',
street: 'Examplestreet 38',
email: {
address: 'max#example.com',
verified: false
}
},
token: {
custom: 'kka',
public: 'fsavvsadgga'
}
}
Does anyone know an good solution for this? I already found more solutions if I only want to change one field (Dynamically set property of nested object), but no solution for more than one field with one method
I think you are stuck with using a function but you could write it yourself. No need for a lib:
function set(obj, path, value) {
let parts = path.split(".");
let last = parts.pop();
let lastObj = parts.reduce((acc, cur) => acc[cur], obj);
lastObj[last] = value;
}
set(user, 'details.email.verified', false);
if what you want to do is merge 2 objects then it is a bit trickier:
function forEach(target, fn) {
const keys = Object.keys(target);
let i = -1;
while (++i < keys.length) {
fn(target[keys[i]], keys[i]);
}
}
function setValues(obj, src) {
forEach(src, (value, key) => {
if (value !== null && typeof (value) === "object") {
setValues(obj[key], value);
} else {
obj[key] = value;
}
});
}
let obj1 = {foo: {bar: 1, boo: {zot: null}}};
let obj2 = {foo: {baz: 3, boo: {zot: 5}}};
setValues(obj1, obj2);
console.log(JSON.stringify(obj1));
One solution in combination with lodash _.set method could be:
function setObject(obj, paths) {
for (const p of Object.keys(paths)) {
obj = _.set(obj, p, paths[p]);
}
return obj;
}

Javascript proxy a collection to single object

I've never used Proxy before, but I think it should be possible to "merge" an collection of objects into a single object.
It needs to remain "live" because the original fields will have value changes performed on them.
Ignore key collisions at this stage:
Given:
const fields = [{
name: 'hello',
value: 1
},{
name: 'goodbye',
value : 2
}];
Output:
const proxy = { hello:1 , goodbye :2 }
I definitely need to be able to iterate over the proxied object with a for in.
Have start a pen here, but haven't got very far: https://codepen.io/anon/pen/mMRaKw?editors=1111
Is it possible?
Here is a solution with the Proxy target as an empty object (if the Array is proxied, the for in will iterate numbered entries).
const fields = [{name: 'hello',value: 1}, { name: 'goodbye', value: 2}];
let handler = {
get: function(target, name) {
var f = fields.find(f => f.name === name);
return f && f.value;
},
ownKeys: function(target) {
return fields.map(f => f.name);
},
getOwnPropertyDescriptor: function(target, prop) {
return { configurable: true, enumerable: true };
}
};
let prox = new Proxy({}, handler);
// update original
fields[0].value=10;
// change reflected in proxy
console.log('proxy.hello',prox.hello);
for( let i in prox ){
console.log(i)
console.log(prox[i])
}
console.log(prox)
I think you are looking for something like:
const fields = [{name: 'hello',value: 1}, { name: 'goodbye', value: 2}];
let handler = {
get: function(target, name) {
if (name === 'flatten') {
return target.reduce((a, c) => {
a[c.name] = c.value;
return a
}, {});
} else {
return target[name];
}
},
set: function(target, prop, value) {
let obj = target.find(o => o.name === prop);
if(obj) {
obj.value = value;
return true;
}
return false;
}
};
let prox = new Proxy(fields, handler);
console.log('flat obj', JSON.stringify(prox.flatten))
// update original
fields[0].value=10;
// change reflected in proxy
console.log('flatten.hello',prox.flatten.hello);
// update proxy
prox.goodbye = 200;
// change reflected in original
console.log('original', fields[1].value)

Removing object properties with Lodash

I have to remove unwanted object properties that do not match my model. How can I achieve it with Lodash?
My model is:
var model = {
fname: null,
lname: null
}
My controller output before sending to the server will be:
var credentials = {
fname: "xyz",
lname: "abc",
age: 23
}
I am aware I can use
delete credentials.age
but what if I have lots of unwanted properties? Can I achieve it with Lodash?
You can approach it from either an "allow list" or a "block list" way:
// Block list
// Remove the values you don't want
var result = _.omit(credentials, ['age']);
// Allow list
// Only allow certain values
var result = _.pick(credentials, ['fname', 'lname']);
If it's reusable business logic, you can partial it out as well:
// Partial out a "block list" version
var clean = _.partial(_.omit, _, ['age']);
// and later
var result = clean(credentials);
Note that Lodash 5 will drop support for omit
A similar approach can be achieved without Lodash:
const transform = (obj, predicate) => {
return Object.keys(obj).reduce((memo, key) => {
if(predicate(obj[key], key)) {
memo[key] = obj[key]
}
return memo
}, {})
}
const omit = (obj, items) => transform(obj, (value, key) => !items.includes(key))
const pick = (obj, items) => transform(obj, (value, key) => items.includes(key))
// Partials
// Lazy clean
const cleanL = (obj) => omit(obj, ['age'])
// Guarded clean
const cleanG = (obj) => pick(obj, ['fname', 'lname'])
// "App"
const credentials = {
fname:"xyz",
lname:"abc",
age:23
}
const omitted = omit(credentials, ['age'])
const picked = pick(credentials, ['age'])
const cleanedL = cleanL(credentials)
const cleanedG = cleanG(credentials)
Get a list of properties from model using _.keys(), and use _.pick() to extract the properties from credentials to a new object:
var model = {
fname:null,
lname:null
};
var credentials = {
fname:"xyz",
lname:"abc",
age:23
};
var result = _.pick(credentials, _.keys(model));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
If you don't want to use Lodash, you can use Object.keys(), and Array.prototype.reduce():
var model = {
fname:null,
lname:null
};
var credentials = {
fname:"xyz",
lname:"abc",
age:23
};
var result = Object.keys(model).reduce(function(obj, key) {
obj[key] = credentials[key];
return obj;
}, {});
console.log(result);
You can easily do this using _.pick:
var model = {
fname: null,
lname: null
};
var credentials = {
fname: 'abc',
lname: 'xyz',
age: 2
};
var result = _.pick(credentials, _.keys(model));
console.log('result =', result);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
But you can simply use pure JavaScript (specially if you use ECMAScript 6), like this:
const model = {
fname: null,
lname: null
};
const credentials = {
fname: 'abc',
lname: 'xyz',
age: 2
};
const newModel = {};
Object.keys(model).forEach(key => newModel[key] = credentials[key]);
console.log('newModel =', newModel);
Lodash unset is suitable for removing a few unwanted keys.
const myObj = {
keyOne: "hello",
keyTwo: "world"
}
unset(myObj, "keyTwo");
console.log(myObj); /// myObj = { keyOne: "hello" }
Here I have used omit() for the respective 'key' which you want to remove... by using the Lodash library:
var credentials = [{
fname: "xyz",
lname: "abc",
age: 23
}]
let result = _.map(credentials, object => {
return _.omit(object, ['fname', 'lname'])
})
console.log('result', result)
You can use _.omit() for emitting the key from a JSON array if you have fewer objects:
_.forEach(data, (d) => {
_.omit(d, ['keyToEmit1', 'keyToEmit2'])
});
If you have more objects, you can use the reverse of it which is _.pick():
_.forEach(data, (d) => {
_.pick(d, ['keyToPick1', 'keyToPick2'])
});
To select (or remove) object properties that satisfy a given condition deeply, you can use something like this:
function pickByDeep(object, condition, arraysToo=false) {
return _.transform(object, (acc, val, key) => {
if (_.isPlainObject(val) || arraysToo && _.isArray(val)) {
acc[key] = pickByDeep(val, condition, arraysToo);
} else if (condition(val, key, object)) {
acc[key] = val;
}
});
}
https://codepen.io/aercolino/pen/MWgjyjm
This is my solution to deep remove empty properties with Lodash:
const compactDeep = obj => {
const emptyFields = [];
function calculateEmpty(prefix, source) {
_.each(source, (val, key) => {
if (_.isObject(val) && !_.isEmpty(val)) {
calculateEmpty(`${prefix}${key}.`, val);
} else if ((!_.isBoolean(val) && !_.isNumber(val) && !val) || (_.isObject(val) && _.isEmpty(val))) {
emptyFields.push(`${prefix}${key}`);
}
});
}
calculateEmpty('', obj);
return _.omit(obj, emptyFields);
};
For array of objects
model = _.filter(model, a => {
if (!a.age) { return a }
})
Recursively removing paths.
I just needed something similar, not removing just keys, but keys by with paths recursively.
Thought I'd share.
Simple readable example, no dependencies
/**
* Removes path from an object recursively.
* A full path to the key is not required.
* The original object is not modified.
*
* Example:
* const original = { a: { b: { c: 'value' } }, c: 'value' }
*
* omitPathRecursively(original, 'a') // outputs: { c: 'value' }
* omitPathRecursively(original, 'c') // outputs: { a: { b: {} } }
* omitPathRecursively(original, 'b.c') // { a: { b: {} }, c: 'value' }
*/
export const omitPathRecursively = (original, path, depth = 1) => {
const segments = path.split('.')
const final = depth === segments.length
return JSON.parse(
JSON.stringify(original, (key, value) => {
const match = key === segments[depth - 1]
if (!match) return value
if (!final) return omitPathRecursively(value, path, depth + 1)
return undefined
})
)
}
Working example: https://jsfiddle.net/webbertakken/60thvguc/1/
While looking for a solution that would work for both arrays and objects, I didn't find one and so I created it.
/**
* Recursively ignore keys from array or object
*/
const ignoreKeysRecursively = (obj, keys = []) => {
const keyIsToIgnore = (key) => {
return keys.map((a) => a.toLowerCase()).includes(key)
}
const serializeObject = (item) => {
return Object.fromEntries(
Object.entries(item)
.filter(([key, value]) => key && value)
.reduce((prev, curr, currIndex) => {
if (!keyIsToIgnore(curr[0]))
prev[currIndex] =
[
curr[0],
// serialize array
Array.isArray(curr[1])
? // eslint-disable-next-line
serializeArray(curr[1])
: // serialize object
!Array.isArray(curr[1]) && typeof curr[1] === 'object'
? serializeObject(curr[1])
: curr[1],
] || []
return prev
}, []),
)
}
const serializeArray = (item) => {
const serialized = []
for (const entry of item) {
if (typeof entry === 'string') serialized.push(entry)
if (typeof entry === 'object' && !Array.isArray(entry)) serialized.push(serializeObject(entry))
if (Array.isArray(entry)) serialized.push(serializeArray(entry))
}
return serialized
}
if (Array.isArray(obj)) return serializeArray(obj)
return serializeObject(obj)
}
// usage
const refObject = [{name: "Jessica", password: "ygd6g46"}]
// ignore password
const obj = ignoreKeysRecursively(refObject, ["password"])
// expects returned array to only have name attribute
console.log(obj)
let asdf = [{"asd": 12, "asdf": 123}, {"asd": 121, "asdf": 1231}, {"asd": 142, "asdf": 1243}]
asdf = _.map(asdf, function (row) {
return _.omit(row, ['asd'])
})

Categories

Resources