JavaScript: remove all but 1 key from an object [duplicate] - javascript

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 5 years ago.
I have an object and I want to remove all values except the one that matches a particular key. For example, I could do this:
function remove(obj, key) {
var value = obj[key]
var ret = {}
ret[key] = obj[key]
obj = ret
}
Or I could iterate:
for (var k in obj) {
if (k != key) {
delete obj[k]
}
}
But I'm wondering if there's a better way. Creating a temporary variable and iterating over the entire object both seem unnecessary. My initial attempt was:
obj = {
key: obj[key]
}
But that resulted in an object with a key of key.

You can indeed achieve what you described without using temporary variables.
function remove(obj, key) {
return Object.assign({}, { [key] : obj[key]});
}

You can just create a new object with [key]:obj[key].
var obj = {
"a":1,
"b":2
};
var key = "a";
function filterByKey(object, key) {
return Object.create({[key]:obj[key]});
}
function filterByKey2(object, key) {
return {[key]:obj[key]};
}
console.log(filterByKey(obj, key));
console.log(filterByKey2(obj, key));

Related

Recursive javascript function that converts nested object keys to string and store all keys in arrray

I am trying to write a javascript recursive function that receives one parameter - nested JSON object.
The function goes through the potentially infinitely nested object and converts all the keys (property names) to a string that is stored in array. Array is returned to a place where the function was called.
Example of JSON object:
{
OBJECT1: {
ATTRIBUTE3: {
PARAMETER2: {
PROPERTY1: {
}
}
}
}
}
The object does not hold any values.
What i tried and did not work:
function convertKeysToString(obj) {
let keys = [];
for (let key in obj) {
if (typeof obj[key] === 'object') {
keys = keys.concat(convertKeysToString(obj[key]));
} else {
keys.push(key.toString());
}
}
return keys;
}
As a result, I expected that returned key is pushed to an array, but the funciton didnt get the key at all or was not pushed to keys array.
Another code I tried:
function getNestedObjectKeys(obj) {
var keys = []
var firstLevel = null
var property = Object.keys(obj)
property = property[0]
firstLevel = Object.keys(obj[property])[0]
if (firstLevel == undefined) {
return 0
}
let returnedValue = keys.unshift(getNestedObjectKeys(obj[property]))
if (returnedValue == 0) {
return Object.keys(obj[property])[0]
}
returnedValue = Object.keys(obj[property])[0]
if (returnedValue != obj[property[0]]) {
return Object.keys(obj[property])[0]
}
else if (returnedValue == firstLevel) {
return keys
}
}
The function should return the key name and push (unshift) it to string and then return it, but the unshift doesnt do what I expect and in the returnedValue is not a expected returned string.
I approached it the way that the function findd the deepest (empty) object, and starts returning the name of the key. The thing is that I must return the key name AND push it to the string, which I can't find the way to accomplish at once.
Your first solution is pretty close, but has one problem (well, one main problem): when the value is type object, you don't add its key to the array. So how is it supposed to get into the array? Give this a shot:
function convertKeysToString(obj) {
let keys = [];
for (let key in obj) {
keys.push(key.toString());
if (typeof obj[key] === 'object') {
keys = keys.concat(convertKeysToString(obj[key]));
}
}
return keys;
}
Other things you may want to consider:
typeof null is object.
typeof [] is also object.
You could have a look to object, which are truthy and typeof object.
const
getKeys = object => (keys => [
...keys.flatMap(key => object[key] && typeof object[key] === 'object'
? [key, ...getKeys(object[key])]
: [key]
)
])(Object.keys(object)),
data = { OBJECT1: { ATTRIBUTE3: { PARAMETER2: { PROPERTY1: {} } } } },
result = getKeys(data);
console.log(result);

how to unify an object from objects [duplicate]

This question already has answers here:
One liner to flatten nested object
(19 answers)
Closed 3 months ago.
good night, I'm having trouble merging an object inside another
my object currently.
{
"id":7,
"name":"Pedroo",
"email":"pedro#hotmail.com",
"cognitoSub":"9162b350-d19db1b3f",
"phoneNumber":"+5521997221764",
"photo":null,
"createdAt":"2022-10-21T14:48:36.000Z",
"updatedAt":"2022-10-21T14:48:36.000Z",
"Account":{
"userId":7
}
}
and I would like to leave it in a single object
example:
{
"id":7,
"name":"Pedroo",
"email":"pedro#hotmail.com",
"cognitoSub":"9162b350-d19db1b3f",
"phoneNumber":"+5521997221764",
"photo":null,
"createdAt":"2022-10-21T14:48:36.000Z",
"updatedAt":"2022-10-21T14:48:36.000Z",
"userId":7
}
Try this method
const flattenObj = (ob) => {
// The object which contains the
// final result
let result = {};
// loop through the object "ob"
for (const i in ob) {
// We check the type of the i using
// typeof() function and recursively
// call the function again
if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
const temp = flattenObj(ob[i]);
for (const j in temp) {
// Store temp in result
result[j] = temp[j];
}
}
// Else store ob[i] in result directly
else {
result[i] = ob[i];
}
}
return result;
};

How to save path to specific property of object in variable [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Fastest way to flatten / un-flatten nested JavaScript objects
(17 answers)
Closed 3 years ago.
Let's say I have object like this:
let object = {
inner: {
inInner: {
a: 5
}
}
}
and I want to store path to property a in variable so I can access it like this:
object[pathToProperty]
Thank you for any suggestions
You can import Lodash, and use it like this:
var path = 'inner.inInner';
var value = _.get(object, path);
You could take a Proxy and address the inner key.
let object = { inner: { inInner: { a: 5 } } },
proxy = new Proxy(object, {
find: function (o, k) {
var value;
if (k in o) return o[k];
Object.values(o).some(v => {
if (v && typeof v === 'object') {
return value = this.find(v, k);
}
});
return value;
},
get: function(obj, prop) {
return prop in obj ?
obj[prop] :
this.find(obj, prop);
}
});
console.log(proxy.a);

How to set all values of an object to null in JavaScript?

I need to set all properties of some object to null.
But the object can be very big, so I can't just do it one by one.
How to set all properties at once?
Here's a useful function called 'Object.keys()', it returns all of the attribute names of an object.
let setAll = (obj, val) => Object.keys(obj).forEach(k => obj[k] = val);
let setNull = obj => setAll(obj, null);
Non-arrow-function version:
function setAll(obj, val) {
/* Duplicated with #Maksim Kalmykov
for(index in obj) if(obj.hasOwnProperty(index))
obj[index] = val;
*/
Object.keys(obj).forEach(function(index) {
obj[index] = val
});
}
function setNull(obj) {
setAll(obj, null);
}
If you are looking for a short one-liner to copy and paste, use this
Object.keys(obj).forEach((i) => obj[i] = null);
Another way of doing it, using Array.reduce. It does not overwriting the existing object. This only works if the object only have simple values.
const newObj = Object.keys(originalObj).reduce(
(accumulator, current) => {
accumulator[current] = null;
return accumulator
}, {});
You can use Object.keys() as Nianyi Wang mentioned in his answer, or a for in, like this:
for (key in obj) {
if (obj.hasOwnProperty(key)) {
obj[key] = null;
}
}
But in this case you should check hasOwnProperty().
But the object can be very big, so I can't just do it one by one.
By "big" do you mean "millions of properties" and you are concerned about performance? Or do you mean "a bunch of properties you don't know the names of, and/or don't want to have list out"?
How to set all properties at once?
You can't. One way or another, you have to loop.
Instead of mutating an existing object, consider creating a new, empty object. Its property values will be undefined, but that could work depending on your code structure.
Lodash can manage this using cloneDeepWith.
My solution to the same problem:
import * as _ from 'lodash';
const bigObj = {"big": true, "deep": {"nested": {"levels": "many" } } };
const blankObj = _.cloneDeepWith(bigObj, (value) => {return _.isObject(value) ? undefined : null});
console.log(blankObj);
// outputs { big: null, deep: { nested: { levels: null } } }
Returning undefined in the customizer was not obvious to me, but this answer explains that doing so triggers recursion.
If object contains child object, if you want to set all child object properties to null, recursive solution is below.
function setEmpty(input){
let keys = Object.keys(input);
for( let key of keys ){
if(typeof input[key] != "object" ){
input[key] = null;
}else{
setEmpty(input[key]);
}
}
return input;
}
you can use for in. Here is an example:
let obj = {prob1:"value1", prob2:"value2"}
for(let prob in obj){obj[prob]=null}
export const setObjToNull = (obj) => {
var returnObj = {};
Object.keys(obj).map((key) => {
let nullObj = { [key]: '' };
Object.assign(returnObj, nullObj);
})
return returnObj;
}
You can use Object.fromEntries & Object.entries like this
Object.fromEntries(
Object.keys(obj).map((key) => [key, null])
)
let values = {
a:1,
b:'',
c: {
a:'',
s:4,
d: {
q: '',
w: 8,
e: 9
}
}
}
values;
const completeWithNull = (current) => {
Object.keys(current).forEach((key) => {
current[key] = current[key] === ''? null
: typeof current[key] === 'object' ? completeWithNull(current[key])
: current[key]
});
return current;
};
completeWithNull(values);

Set an object property by using its value [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 8 years ago.
Say I call following function:
var query = makeQuery("email", "foo#bar.com");
The implementation I have is:
makeQuery = function (key, value) {
return { key: value};
}
The object I end up with is: {"key": "foo#bar.com"}, which is obviously wrong. I would like to obtain {"email": "foo#bar.com"} instead. I tried setting it like so:
makeQuery = function (key, value) {
return { JSON.stringify(key): value};
}
... but I get a "SyntaxError: Unexpected token ." I've also thought of using toString() and even eval(), without success. So my problem is to be able to set the property of the object returned in makeQuery() using its real value, that is, pick up the value of 'key', not setting the property with the 'key' literal.
Thanks for the help.
Create the object first and then use the square bracket syntax so you can set the property using the value of key:
makeQuery = function (key, value) {
var query = {};
query[key] = value;
return query;
};
For variable keys in objects, use
var obj[key] = value
So then it becomes:
function makeQuery(key, value) {
var obj = {};
obj[key] = value;
return obj;
}
define an object..
makeQuery = function (key, value) {
var o = {};
o[key] = value;
return o;
}

Categories