I have a dynamic object :
input: {
key1: 'text1',
key2: 10000,
key3: 3456,
key4: 'text2',
key5: ['v1','v2','v3'] .....
}
I would like to reset it to
output
{
key1: '',
key2: 0,
key3: 0,
key4: '',
key5: []
.......
}
I didn't find any direct method to do this, I know to do this with looping. I was wondering if we have best method/best practices to acheive output.
You could take Object.assign with an object of the wanted values.
This method does not replace unknown properties. In this case, you need a new object, or you need to delete all propeties in advance.
const
values = { key1: '', key2: 0, key3: 0, key4: '', key5: [] },
input = { key1: 'text1', key2: 10000, key3: 3456, key4: 'text2', key5: ['v1','v2','v3'] };
Object.assign(input, values);
console.log(input);
A dynamic object with deleting own enumerable properties.
const
values = { key1: '', key2: 0, key3: 0, key4: '', key5: [] },
input = { foo: '42', bar: '101', key1: 'text1', key2: 10000, key3: 3456, key4: 'text2', key5: ['v1','v2','v3'] };
Object.keys(input).forEach(Reflect.deleteProperty.bind(null, input));
Object.assign(input, values);
console.log(input);
You can define all the default values in an object, and use the spread operator
let input = {key1:'text1', key2:10000, key3:3456, key4:'text2', key5:['v1','v2','v3']}
const defaultValues = {key1:'', key2:0, key3:0, key4:'', key5:[]}
input = {
...defaultValues
}
console.log(input)
You can loop through all the elements in the object and based on the type of the property we can reset it to default value. Below is the example.
let input = {key1:'text1', key2:10000, key3:3456, key4:'text2', key5:['v1','v2','v3']}
const resetData = (data) => {
let keys = Object.keys(data);
let dataCopy = {};
keys.forEach(key => {
if(Array.isArray(data[key])) {
dataCopy[key] = []
} else if(typeof data[key] === "object") {
dataCopy[key] = {}
} else if(typeof data[key] === "string") {
dataCopy[key] = ""
} else {
dataCopy[key] = 0
}
})
return dataCopy;
}
console.log(resetData(input));
input = {key6: {abc: "123"}, key7: "dummy", key8: [1, 2, 3] }
console.log(resetData(input));
Related
I have an object and for all keys that have a null value I want to replace this null with an empty string (or a dash in my case)?
For example
Obj = {
key1: null,
key2: null,
key3: true,
...
key_n: null
}
Turns into
Obj = {
key1: "-",
key2: "-",
key3: true,
...
key_n: "-"
}
This will work.
const Obj = {
key1: null,
key2: null,
key3: true,
key_n: null
};
for (const key in Obj) {
const val = Obj[key];
if (val === null) {
Obj[key] = "-";
}
}
console.log(Obj);
const obj = {
key1: null,
key2: null,
key3: true,
key_n: null
};
Object
.entries(obj)
.forEach(function ([key, value]) {
if (value === null) {
this[key] = '-';
}
}, obj); // make use of `forEach`'s `thisArg` parameter.
console.log({ obj });
You just have to match whether a key's corresponding value is null or not , if yes then change it to underscore.
Obj = {
key1: null,
key2: null,
key3: true,
key_n: null
}
Object.keys(Obj).map(key=>{
if(!Obj[key])Obj[key] = "_"
})
console.log(Obj)
So lets say I have an object like this:
myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
And I want an array of the keys, but only if the have a value. i.e. if they're undefined or empty string, I don't want them included in the array.
Currently I'm using Object.keys(myObject) but this gets all the keys including those that are undefined, false or nullable value.
I completely understand I can likely write my own version of the keys method from Object, but I'm wondering if there's an easier way than that.
Filter the entries by whether the key portion of the entry is truthy, then map to the keys:
const myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
};
const keys = Object.entries(myObject)
.filter(([, val]) => val)
.map(([key]) => key);
console.log(keys);
You only need to use Array.filter() to remove the keys that have nullable results
const myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
};
const keys = Object.keys(myObject)
.filter(key => myObject[key])
console.log(keys);
If all you care about are the truthy keys you can use a somewhat simpler filter than above:
myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
truthyKeys = Object
.keys(myObject) // array of all keys
.filter(k => myObject[k]) // filter out ones with falsy values
console.log(truthyKeys)
const myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
};
const keys = Object.keys(myObject).filter(key => myObject[key]);
This will also cut out other falsy values however, such as 0, NaN, null, false. If you very specifically are guarding against empty strings and undefined:
const myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
};
const keys = Object.keys(myObject)
.filter(key => myObject[key] !== '' && myObject[key] !== undefined);
I don't know if there is another way but you can try something like this
myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
const getValue = (obj) => {
const array = [];
for (const [key, value] of Object.entries(obj)) {
if(value){
array.push(key);
}
}
return array;
}
console.log(getValue(myObject));
let objectWithTruthyKeys = Object.keys(myObject).filter(i => myObject[i]);
Explanation:
Object.keys will get all the keys of the property (including the ones that contain falsy values).
The filter will go through each key in myObject (represented by i). the condition will be true only if the value is truthy, hence, filtering out the keys which contain falsy values.
There's a couple ways to do that. You could use filter:
const myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
var keysWithValues = Object.keys(myObject).filter(key => myObject[key]);
console.log(keysWithValues);
Or a for loop:
const myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
var keysWithValues = [];
for (const [key, value] of Object.entries(myObject)) {
if (value) {
keysWithValues.push(key);
}
}
console.log(keysWithValues);
You could also be fancy and extend Object by creating a class. But I believe that would be overkill :D
try it.
myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
let x= Object.entries(myObject);
for(i=0;i<x.length;i++){
if(x[i][1]!==undefined&&x[i][1]!==""){
console.log(x[i][0])}
}
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 2 years ago.
I have an array of objects, similar to the below:
const objectArray = [
{
key1: 'value1a',
key2: 'value2a',
key3: 'value3a',
},{
key1: 'value1b',
key2: 'value2b',
key3: 'value3b',
},{
key1: 'value1c',
key2: 'value2c',
key3: 'value3c',
},
];
and I would like to get an array containing all the values stored in, say, key2.
At the moment, my code looks as follows:
const valueArray = [];
objectArray.forEach((object) => {
valueArray.push(object.key2);
});
This then results in
const valueArray = ['value2a', 'value2b', 'value2c'];
It feels like there is probably a more eloquent way to achieve the same thing, in just one line but I can't for the life of me figure out how to do that - can someone point me towards some documentation, or example code on how to do that please
Array.prototype.map()
const objectArray = [
{
key1: 'value1a',
key2: 'value2a',
key3: 'value3a',
},
{
key1: 'value1b',
key2: 'value2b',
key3: 'value3b',
},
{
key1: 'value1c',
key2: 'value2c',
key3: 'value3c',
},
];
const result = objectArray.map(obj => obj.key2);
console.log(result);
You can map objectArray:
const valueArray = objectArray.map(o => o.key2);
You can use Array#map (which creates a new array with the result of applying a callback with each element) with destructuring.
const objectArray = [
{
key1: 'value1a',
key2: 'value2a',
key3: 'value3a',
},{
key1: 'value1b',
key2: 'value2b',
key3: 'value3b',
},{
key1: 'value1c',
key2: 'value2c',
key3: 'value3c',
},
];
const res = objectArray.map(({key2})=>key2);
console.log(res);
Here is how you can do it for any key:
const objectArray = [
{
key1: 'value1a',
key2: 'value2a',
key3: 'value3a',
}, {
key1: 'value1b',
key2: 'value2b',
key3: 'value3b',
}, {
key1: 'value1c',
key2: 'value2c',
key3: 'value3c',
},
];
function getByKey(key) {
return objectArray.reduce((acc, red) => acc = [...acc, red[key]], [])
}
console.log(getByKey("key2"));
Question In JavaScript Form
I have an object like this:
const obj1 = {key1: value1, key2: value2, key3: value3, ...}
To change value of key1 (can be any key), this is my way:
const obj2 = {...obj1, key1: newValue}
I want to set all keys to some newValue, how to do it without mutation?
Wanted Output:
{key1: newValue, key2: newValue, key3: newValue, ...}
Question In Redux Form
I have my state like this:
{
key1: value1,
key2: value2,
key3: value3,
// ...
}
To change one value, I am doing like this in my reducer:
return {
...state,
[action.key]: action.value
}
But how to change value of all the keys if I give some value through my action.value? I want my next state like this:
{
key1: newValue,
key2: newValue,
key3: newValue,
// ...
}
You need to loop over keys, and create a new object using say reduce
const obj = {
key1: 1,
key2: 2,
key3: 3
}
const value = 0;
const updated = Object.keys(obj).reduce((acc, key) => (acc[key] = value, acc), {})
console.log(obj, updated)
Just for fun some proxy magic (do not use for production)
const obj = {
key1: 1,
key2: 2,
key3: 3
}
const value = 0
const updated = { ...new Proxy(obj, {
keys() {
return Object.keys(obj)
},
get() {
return value
}
})
}
console.log(obj, updated)
I have an array of objects and I want to get a new array with objects that will have only some of the initial values.
var obj = [{
key1: 'someValue',
key2: 'someValue',
key3: 'someValue'
}, {
key1: 'someValue2',
key2: 'someValue2',
key3: 'someValue2'
}]
I am looking something like Underscore's _.pluck but for more than one values that will give me as a result.
[{
key1: 'someValue',
key2: 'someValue'
}, {
key1: 'someValue2',
key2: 'someValue2'
}]
If there are multiple items in object and you want to only keep few, you can use pick.
_.map(arr, o => _.pick(o, ['key1', 'key2']))
Demo
You can use map with omit.
_.map(arr, o => _.omit(o, 'key3'))
Demo
This is fairly easy with JavaScript's built-in map:
Using an ES2015 arrow function:
var newArray = initialArray.map(e => ({key1: e.key1, key2: e.key2}));
var initialArray = [
{key1: 'someValue', key2: 'someValue', key3: 'someValue'},
{key1: 'someValue2', key2: 'someValue2', key3: 'someValue2'}
];
var newArray = initialArray.map(e => ({key1: e.key1, key2: e.key2}));
document.body.innerHTML = "<pre>" + JSON.stringify(newArray, null, 2) + "</pre>";
Using an old-style function:
var newArray = initialArray.map(function(entry) {
return {key1: entry.key1, key2: entry.key2};
});
var initialArray = [
{key1: 'someValue', key2: 'someValue', key3: 'someValue'},
{key1: 'someValue2', key2: 'someValue2', key3: 'someValue2'}
];
var newArray = initialArray.map(function(entry) {
return {key1: entry.key1, key2: entry.key2};
});
document.body.innerHTML = "<pre>" + JSON.stringify(newArray, null, 2) + "</pre>";
map calls the callback once for each entry in an array, and builds a new array out of the values you return from the callback. So in the above, we're returning new objects with just key1 and key2.
(I renamed obj to initialArray because while arrays are objects, I wanted to emphasize that we were dealing with an array.)