I have a field object that can contain only one of different properties with an id as a value.
const Field = {
// Field can contain
property1Id: 'someId',
// Or
property2Id: 'someOtherId',
// Or
property3Id: '...'
//...
};
I want to return the property name and it's value. The following works fine but feels a bit long. Anyway to reduce it / be more efficient.
const propertyName = Field.property1Id
? 'Property 1'
: someObject.property2Id
? 'Property 2'
: someObject.property3Id
? 'Property 3'
: 'Other';
const id = Field.object1Id
? Field.property1Id
: Field.property2Id
? Field.property2Id
: Field.property3Id
? Field.property3Id
: null;
console.log(propertyName, id)
Thanks.
If this is what you mean, every property name with property value is returned :)
const Field = {
// Field can contain
property1Id: 'someId',
// Or
property2Id: 'someOtherId',
// Or
property3Id: '...'
//...
}
let entries = Object.entries(Field);
entries.forEach(entry => {
console.log(entry)
})
Best approach
const Field = {
// Field can contain
property1Id: 'someId',
// Or
property2Id: 'someOtherId',
// Or
property3Id: '...'
//...
};
let i = 0;
for (const property in Field) {
i++
console.log('Property ' + i, Field[property]);
}
Output:
"Property 1" "someId"
"Property 2" "someOtherId"
"Property 3" "..."
Related
I want to do change the name of a key in an Object. But when I want to do this with an if condition, I get this (Assignment to function parameter 'key') error. How can i manipulate a key name ?
My Code:
const personData = [];
Object.keys(testItem).forEach((key) => {
item = testItem[key];
if (key === 'Name'){
key = 'Person Name';
}
personData.push({ name: key, data: Object.values(item) })
});
testItem data:
testItem = {Name: {...}, Surname: {...}}
I want the Name key to change to Person Name without error.
The key variable was taken in as input for the foreach function, and you shouldn't modify it - it is meant as a read only variable. An alternative that doesn't modify the key variable would be
const personData = [];
Object.keys(testItem).forEach((key) => {
let newKey = key;
item = testItem[key];
if (key === 'Name'){
newKey = 'Person Name';
}
personData.push({ name: newKey, data: Object.values(item) })
});
I didn't get what you wanted to do, simply assign keys value to new key and delete previous one for example :
const personData = {
Name: 'John',
lastname: 'Doe'
};
personData.PersonName = personData.Name
delete personData.Name;
console.log(personData.PersonName)
This is my object.
values : {
title : 'this is title ..',
translate : {
en : 'some texts .. ',
},
}
And this is array I have.
arr = ['translate.en', 'title'];
What I want to do is this, but this is not work as I expected.
const value = arr.map(item => values[item]);
// (Result) value : undefined, 'this is title ..'
// (Expected) value : 'some texts .. ', 'this is title ..'
const value = arr.map(item => values.item); // error : 'item' is declared but its value is never read.
How to get values.translate.en value using map()?
you can use this snippet. Not the cleanest, but you get the idea
arr.map(item => {
let arrItem = item.split('.');
let data = values;
for (i in arrItem) {
data = data[arrItem[i]];
}
return data;
});
Your current code is doing the following:
const values = {
title: 'this is title ..',
translate: {
en: 'some texts .. ',
},
'translate.en': 'hello',
};
const arr = ['translate.en', 'title'];
const value = arr.map((item) => values[item]);
// (Result) value : 'hello', 'this is title ..'
If you want to do what you want to do, you should do the following:
const values = {
title: 'this is title...',
translate: {
en: 'some texts... ',
},
};
const arr = ['translate.en', 'title'];
const value = arr.map((item) => {
let index = item.split('.');
let value = values;
for (i in index) {
value = value[index[i]];
}
return value;
});
// (Result) value : 'come texts...', 'this is title ..'
However, if possible, I would suggest structuring your values object in the following way:
const values = {
title: {
kr: '타이틀',
en: 'title'
},
body: {
en: 'some texts .. ',
kr: '어쩌고 저쩌고 .. ',
},
};
So as long as you know which part: body or title is required and you know the language you want to get, it will be easy to get it.
axios.post('saveUser', {id, name})
If name is empty how could I exclude it in the param? if I put ({id, name}), isn't the method would still have a property of name undefined?
I don't want this
const obj = {id: 123, name: undefined}
I want this const obj = {id: 123}
but I don't want to create a temporary variable like so
let obj = { id: id }; if(name) obj = { ...obj, name };
I would suggest you adding object properties conditionally with ES6 syntax like this.
const normalizeData = ({id, name = ""}) => {
const condition = !!name; // Equivalent to: name !== undefined && name !== "";
return {id, ...(condition && { name })};
}
console.log(normalizeData({id: 123, name: ""}));
console.log(normalizeData({id: 123, name: undefined}));
console.log(normalizeData({id: 123, name: "Phong_Nguyen"}));
Explain:
Using Default function parameters at line code name = "" to avoid undefined of name propety having not included in input object.
Using Destructuring assignment at line code ...(condition && { name })
You can create the object with the id first and then add a name afterwards:
const obj = {id: 123};
if(name) obj.name = name;
axios.post('saveUser', obj);
I do not know why I got Uncaught SyntaxError for this code
const relationship2 = {
name = 'zero',
friends: ['nero', 'hero', 'xero'],
logFriends() {
this.friends.forEach(friend => {
console.log(this.name, frined);
});
},
};
Object needs key/value pair which are seprated by :not =
change this
name = 'zero',
to this
name : 'zero',
Suppose I want to destructure my function argument like this
const func = ({field: {subField}}) => subField;
How can I prevent this from throwing an error if field is undefined or null ?
You might use a default value:
const func = ({field: {subField} = {}}) => subField;
It works only with {field: undefined} though, not with null as a value. For that I'd just use
const func = ({field}) => field == null ? null : field.subField;
// or if you don't care about getting both null or undefined respectively
const func = ({field}) => field && field.subField;
See also javascript test for existence of nested object key for general solutions.
You could only part destruction and use for subField a parameter with a check.
var fn = ({ field }, subField = field && field.subField) => subField;
console.log(fn({ field: null }));
A good way to fix both the cases of null and undefined is the following
const func = ({field}) => {
let subField = null;
if(field) {
({subField} = field);
}
return subField
};
If you only want to handle the case when field is undefined, you could just to
const func = ({field: {subField} = {}}) => subField;
whereby if field is undefined the default empty object is used as its value