How can I map an object in order to change it? - reactjs

I need to map an object
obj={a:'',b:firstname,c:'',d:lastname}
while mapping if an element of an object does contain : '', i will return to to null so the result will be like that :
obj={a:null,b:firstname,c:null,d:lastname}.
How can I do that?

You can use Object.keys to get an array of all the property names in the object, and then use reduce to build up a new object where all properties with value '' get the value null instead.
const obj = { a: "", b: "foo", c: "", d: "bar" };
const result = Object.keys(obj).reduce((acc, key) => {
acc[key] = obj[key] === '' ? null : obj[key];
return acc;
}, {});
console.log(result);

You can do this by using for in
var obj = {a:'',b:'firstname',c:'',d:'lastname'}
for(var key in obj){
if(obj[key] === ""){
obj[key] = null
}
}
console.log(obj)

Related

ReactJs - TypeError: Cannot assign to read only property 'name' of object '#<Object>'

I have an array of objects:
var subcategories = [{name:'gloves', tag:'wool'}, {name:'boots', tag: 'leather'}]
All I want to do is to find the index of the object to change a name or a tag. I use this function:
function setSubcat(val, index, lang){
var newArr = []
var obj = {
'name': val
}
subcategories.map((val, i)=>{
if(index === i){
var newObj = Object.assign(val, obj)
newArr.push(newObj)
}
newArr.push(val)
})
setSubcategories(newArr)
}
The error happens at var newObj = Object.assign(val, obj)
I thought the error means I can't mutate the state directly and so I have to make a copy. I thought that mapping through subcategories and push it into a local newArr means I made a copy of the array. But it wasn't working when I wanted to change a value of object in it so I used Object.assign which I thought would deep copy the particular object from the array, but it's not working either.
What am I missing here?
As pointed in comments:
the code you posted does not show how you created object with unmodifiable property
you can create a new object and not use Object.assign to get rid of the error
use map function in more idiomatic way
interface TaggedItem {
name: string,
tag: string
}
var subcategories = [{name:'gloves', tag:'wool'}, {name:'boots', tag: 'leather'}];
function setSubcat(val: string, index: number, _lang: any){
var obj: Partial<TaggedItem> = {
'name': val
}
var newArr: TaggedItem[] = subcategories.map((val, i)=>{
if(index === i){
return {
...val,
...obj
}
} else {
return {...val};
// or return val; if you don't need a full copy
}
})
console.log(newArr);
}
setSubcat('newName', 0, undefined);
Playground link

How to get value in an object array by key

how can I get value in an object array by a key, which is also in this object array.
the object array looks like this:
const objectArray = [
{key: "1", value: "12321"},
{key: "2", value: "asdfas"}
]
I have now the value of key, e.g. key = 1, but I want to get 12321 as result.
any solution?
You can use .find() to achieve it.
Try this:
Working Demo
this.objectArray.find(x => x.key == "1").value
To handle exception, if the item doesn't exists in the array, do this:
let item = this.objectArray.find(x => x.key == "1")
this.value = item ? item.value : null
You can do this using filter() and use the value of the key you already have.
const objectArray = [
{key: "1", value: "12321"},
{key: "2", value: "asdfas"}
]
const el = objectArray.filter(item => item.key == 1)[0];
el
? console.log(el.value) // gives 12321
: console.log('none listed')
objectArray.find(e => e.key == "1")
ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
objectArray.forEach(function(item) {
Object.keys(item).forEach(function(key) {
console.log("key:" + key + "value:" + item[key]);
});
});

How would I loop through an array of objects and check for existence of key- or value parameter?

Given this Array (key / value pairs):
var array = [
{name: 'Antonello', location:'Barcelona'},
{email: 'george#george.com', name:'George'},
{name: 'Mike', coder: true}
]
how would a function look like that finds the element in an array of objects and returns the index (or -1 if no element of this kind).
NOTICE: this is a beginners exercise and no use of ES6 or findIndex.
This is my code. I want to check if either the key or the value is undefined. If not, return the array index.
function getIndex(array, key, value) {
var indexFound = 0;
for (var index in array) {
if (array[index].key == undefined && array[index].value == undefined) {
var indexFound = -1;
} else {
var indexFound = array[index];
}
}
return indexFound
}
This is the function with the 3 parameters getIndex(array, key, value).
Expected outcome:
getIndex(array, "name", "Antonello") should return 0.
getIndex(array, "coder", false) should return -1.
Your implementation of for...in loop is wrong, check the documentation here, for..in
Although you can use for..in loop for iterating over the array, important thing to note here from Mozilla docs is:-Documentation
Array indexes are just enumerable properties with integer names and are otherwise identical to general object properties. There is no guarantee that for...in will return the indexes in any particular order. The for...in loop statement will return all enumerable properties, including those with non–integer names and those that are inherited.
Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. Therefore, it is better to use a for loop with a numeric index (or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of access is important.
var array = [{
name: 'Antonello',
location: 'Barcelona'
},
{
email: 'george#george.com',
name: 'George'
},
{
name: 'Mike',
coder: true
}
];
function getIndex(array, key, value) {
var indexFound = -1;
array.forEach((obj, index) => {
if (obj[key] !== undefined && obj[key] === value) {
indexFound = index;
}
});
return indexFound;
}
var foundIndex = getIndex(array, 'name', 'Antonello');
console.log(foundIndex);
var array = [
{name: 'Antonello', location:'Barcelona'},
{email: 'george#george.com', name:'George'},
{name: 'Mike', coder: true}
];
function getIndex(array, key, value) {
var indexFound = -1;
array.forEach(function(obj, index) {
if (typeof obj[key] !== 'undefined' && obj[key] === value) {
indexFound = index;
}
});
return indexFound;
}
console.log(getIndex(array, "name", "Antonello"));
console.log(getIndex(array, "email", "george#george.com"));
console.log(getIndex(array, "coder", false));

How to map an array in order to change it?

I need to map an array of objects
array=[{a:'',b:firstname,c:'',d:lastname},{a:'',b:firstname,c:'',d:lastname}]
while mapping if an element of object of the array does contain : '', i will return to to null so the result will be like that :
array=[{a:null,b:firstname,c:null,d:lastname},{a:null,b:firstname,c:null,d:lastname}].
It should do what you expect in your particular case (only with a, b, c keys):
const newArray = array.map(({a,b,c}) => {
return {a: !!a ? a: null, b: !!b : null, !!c : c : null }
})
You could create helper function so you can easily change your condition and mapping.
function transform(array, mapFn) {
return array.map((obj) => {
const newObj = {};
Object.keys(obj).map(function(key) {
newObj[key] = mapFn(obj, key);
});
return newObj;
});
}
const array = [{a:'',b:"f1",c:'',d:"f2"},{a:'',b:"f3",c:'',d:"f4"}];
const newArray = transform(array, (obj, key) => {
const value = obj[key];
return value === '' ? null : value;
})
With this you have full control over mapping function, and later if you have to for example handle not only empty string but also undefined values and map them to null, you can do it easily by providing changed mapFn.

ES6 - Filter an Object based on True values

I have an Object which contains some booleans like this:
{ date: "2017-10-05", name_change: false, age_change: true, ... }
I want to filter() the keys which are true.
I also need the date value. how can I make this filter?
Regards.
Get the keys with Object#keys, and then iterate the array of keys with Array#reduce, and build a new object that doesn't contain keys which value equals to true:
const obj = {
date: "2017-10-05",
name_change: false,
age_change: true
};
const result = Object.keys(obj)
.reduce((o, key) => {
obj[key] !== true && (o[key] = obj[key]);
return o;
}, {});
console.log(result);

Resources