I need to change the value I'm sending. An example of a array is:
0: {name: "One", value: 1}
1: {name: "Two", value: 2}
2: {name: "One", value: 3}
3: {name: "Two", value: 4}
Not important how length array can be. Any time is four object any time only two example:
0: {name: "One", value: 1}
1: {name: "Two", value: 4}
Important is to need to convert value inside object
If I got:
0: {name: "One", value: 1}
1: {name: "Two", value: 2}
2: {name: "One", value: 3}
3: {name: "Two", value: 4}
I need to convert to
0: {name: "One", value: 'Value one'}
1: {name: "Two", value: 'Value two'}
2: {name: "One", value: 'Value three'}
3: {name: "Two", value: 'Value four'}
What i try:
data: convert(ArrayOfData)
convert(arr){
const convertArr = ['Value one', 'Value two', 'Value three', 'Value four'];
return value.map((value: any) => convertArr[value]);
}
This no work i don't know why....
second try also no work....
convert(arr){
let resultArr = arr.map(arr => {
if (arr.value == 1) {
return 'Value one'
}
if (arr.value == 2) {
return 'Value two'
}
})
return resultArr;
}
But according to the code, this should really work ...
4 Answers 4
Seems like you have a misunderstanding about Array.prototype.map()
const convertArr = [, 'Value one', 'Value two', 'Value three', 'Value four'];
value.map(({ name, value }) => ({
name,
value: convertArr[value],
}));
5 Comments
const convertArr = [ , 'Va....], the length is 5-1 every time it traverses, and index also corresponds to its valueconst values = {
"1": "one",
"2": "two",
"3": "three",
"4": "four",
};
const arr = [
{ name: "One", value: 1 },
{ name: "Two", value: 2 },
{ name: "One", value: 3 },
{ name: "Two", value: 4 },
];
const result = arr.map(({ name, value }) => {
return { name, value: `Value ${values[value]}` };
});
console.log(result);
Comments
See the docs about array.map():
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Since your provided function is always returning a string you'll get an array of strings. To get what you want you need instead to return a new item where the value property is changed the a string 'Value one' etc.
function convert(arr){
let resultArr = arr.map(item => {
if (item.value == 1) {
return {...item, value:'Value one'}
}
if (item.value == 2) {
return {...item, value:'Value two'}
}
})
return resultArr;
}
Comments
public someFunc() {
let arr = [{ name: 'One', value: '1' }, { name: 'Two', value: '2' }];
arr = arr.map((item) => {
item.value = `Value ${item.name.toLowerCase()}`;
return item;
});
}
However you originally have value as a number and then convert it to a string, there will be a conflict. Also instead of my logic you can add any other logic, it should do