I have an array of objects that looks like this:
const arr1 = [
{id: 1, name: 'Dave', tax: 123.34543}
{id: 2, name: 'John', tax: 3243.12323}
{id: 3, name: 'Tom', tax: 122.34324}
]
And I am trying to round off the tax value, so in the end the array should look like this:
[
{id: 1, name: 'Dave', tax: 123.34}
{id: 2, name: 'John', tax: 3243.12}
{id: 3, name: 'Tom', tax: 122.34}
]
I tried using the map function like so:
arr1.map(value => Math.round(value.tax * 100)/100);
but instead of getting a modified array of objects, I get an array with only the result of the Math.round which looks like this:
[ 123.34, 3243.12, 122.34]
How do I map the array of objects to get the expected result as described above.
Thanks.
You can update tax in your map function.
See implementation below.
const arr1 = [
{id: 1, name: 'Dave', tax: '123.34543'},
{id: 2, name: 'John', tax: '3243.12323'},
{id: 3, name: 'Tom', tax: '122.34324'},
];
const taxRoundedArray = arr1.map(item => {
let tax = Math.round(item.tax * 100)/100
return {
...item,
tax
}
});
console.log(taxRoundedArray);
You could map new objects with the wanted values.
const
array = [{ id: 1, name: 'Dave', tax: 123.34543 }, { id: 2, name: 'John', tax: 3243.12323 }, { id: 3, name: 'Tom', tax: 122.34324 }],
result = array.map(o => Object.assign({}, o, { tax: Math.round(o.tax * 100) / 100 }));
console.log(result);
You are very close to the correct solution, see below:
arr1.map(value => {
value.tax = Math.round(value.tax * 100)/100);
return value
});
You need to return the altered object otherwise it gets overwritten.
Hope this helps
Lloyd
Array.map processes the entry in array and return the processed value. In the attempt, you were only returning the updated tax, however, you will need to return the object. Try following
const arr1 = [{id: 1, name: 'Dave', tax: 123.34543},{id: 2, name: 'John', tax: 3243.12323},{id: 3, name: 'Tom', tax: 122.34324}];
const arr2 = arr1.map(({tax, ...rest}) => ({...rest, tax: Math.round(tax * 100)/100}));
console.log(arr2);
map over the array and return each object with a new tax value that has been turned to a floating-point number fixed to two decimal places.
const arr1 = [{"id":1,"name":"Dave","tax":"123.34543"},{"id":2,"name":"John","tax":"3243.12323"},{"id":3,"name":"Tom","tax":"122.34324"}];
const arr2 = arr1.map(obj => {
const tax = +Number.parseFloat(obj.tax).toFixed(2);
return { ...obj, tax };
})
console.log(arr2);
You can do:
const arr1 = [
{id: 1, name: 'Dave', tax: '123.34543'},
{id: 2, name: 'John', tax: '3243.12323'},
{id: 3, name: 'Tom', tax: '122.34324'}
];
const result = arr1.map(user => {
user.tax = (Math.round(+user.tax * 100) / 100);
return user;
});
console.log(result);
Related
I have two nested array of objects, how to compare two array of objects by
id from arrobj1 and assignId from arrobj2 using javascript
So, I would to know how to compare array of objects by id and assignId and return array of objects using javascript
Tried
const result = arrobj1.filter(arr1 => {
arrobj2.find(arr2 => arr2.assignId === arr1.id)
});
var arrobj1 =[
{id: 1, name: 'xxx', value:100},
{id: 2, name: 'yyy', value:200},
{id: 3, name: 'zzz', value:400}
]
var arrobj2 =[
{country: 'IN', name: 'lina', assignId:2},
{country: 'MY', name: 'john', assignId:3},
{country: 'SG', name: 'peter', assignId:6}
]
Expected Code:
[
{id: 2, name: 'yyy', value:200},
{id: 3, name: 'zzz', value:400}
]
You have it almost correct, but you need to return in your filter, either by explicitly adding the return keyword or by removing the braces to use the arrow function's implicit return:
const result = arrobj1.filter(arr1 =>
arrobj2.find(arr2 => arr2.assignId === arr1.id)
)
// or
const result = arrobj1.filter(arr1 => {
return arrobj2.find(arr2 => arr2.assignId === arr1.id)
})
We can combine Array.filter() and Array.some() to make it more simple
let result = arrobj1.filter(a1 => arrobj2.some(a2 => a2.assignId === a1.id) )
console.log(result)
For your code,the reason is that you have missing return when invoke find
var arrobj1 =[
{id: 1, name: 'xxx', value:100},
{id: 2, name: 'yyy', value:200},
{id: 3, name: 'zzz', value:400}
]
var arrobj2 =[
{country: 'IN', name: 'lina', assignId:2},
{country: 'MY', name: 'john', assignId:3},
{country: 'SG', name: 'peter', assignId:6}
]
let result = arrobj1.filter(a1 => arrobj2.some(a2 => a2.assignId === a1.id) )
console.log(result)
You can generally go with the filter and some combination as #flyingfox mentioned in the answer, But if you'd have thousands of records then your time complexity would increase which you can solve by removing the nested some loop.
So more performant code would look like the following for a bigger data set.
And yes, Either use return with braces or simply remove the braces for one-liner returns!
var arrobj1 = [
{ id: 1, name: 'xxx', value: 100 },
{ id: 2, name: 'yyy', value: 200 },
{ id: 3, name: 'zzz', value: 400 },
]
var arrobj2 = [
{ country: 'IN', name: 'lina', assignId: 2 },
{ country: 'MY', name: 'john', assignId: 3 },
{ country: 'SG', name: 'peter', assignId: 6 },
]
var obj = {}
for (const elem of arrobj2) {
obj[elem.assignId] = true
}
let result = arrobj1.filter((a1) => obj[a1.id])
console.log(result)
I want to copy value of name and age into another array, below code is working fine, But I wanted to know better way to do it.
const users = [
{ id: 0, name: 'John', age:34 },
{ id: 1, name: 'Wayne', age:44 },
{ id: 2, name: 'David', age:24 },
];
let values=[];
users && users.map(user => {
values.push(user['name'])
values.push(user['age'])
})
console.log(values);
output
['John', 34, 'Wayne', 44, 'David', 24]
You can bind each items to an array containing both its name and age and then flattern these arrays.
This can be done using Array#FlatMap
const users = [
{ id: 0, name: 'John', age:34 },
{ id: 1, name: 'Wayne', age:44 },
{ id: 2, name: 'David', age:24 },
];
const nameAndAges = users.flatMap(user => [user.name, user.age])
console.log(nameAndAges)
Your solution looks good, this can be also solved in different ways, I guess you may want to create function for handling this.
const users = [
{ id: 0, name: 'John', age: 34 },
{ id: 1, name: 'Wayne', age: 44 },
{ id: 2, name: 'David', age: 24 },
];
const result = mapArrayToProps(users, ['name', 'age']);
function mapArrayToProps(arr, props) {
return arr.flatMap(obj => mapObjectToProps(obj, props));
}
function mapObjectToProps(obj, props) {
return props.map(prop => obj[prop])
}
console.log(result);
I'm just learning js now (late to the party I know) and I have the following code and I was wondering if it could be written in a cleaner/simpler way?
Also, ideally, instead of using "if (obj.id === 1)" I would like to iterate through the array and add age based on the sequence i.e. [0] would become '32' and so on.
const students = [ // Three objects, each with four properties
{
id: 1,
name: 'Mark',
profession: 'Developer',
skill: 'JavaScript'
},
{
id: 2,
name: 'Ariel',
profession: 'Developer',
skill: 'HTML'
},
{
id: 3,
name: 'Jason',
profession: 'Designer',
skill: 'CSS'
},
];
const studentsWithAge = students.map(obj => {
if (obj.id === 1) {
return {...obj, age: '32'};
} else if (obj.id === 2) {
return {...obj, age: '26'};
} else if (obj.id === 3) {
return {...obj, age: '28'};
}
return obj;
});
console.log(studentsWithAge);
// output
// [
// {
// id: 1,
// name: 'Mark',
// profession: 'Developer',
// skill: 'JavaScript',
// age: '32'
// },
// {
// id: 2,
// name: 'Ariel',
// profession: 'Developer',
// skill: 'HTML',
// age: '26'
// },
// {
// id: 3,
// name: 'Jason',
// profession: 'Designer',
// skill: 'CSS',
// age: '28'
// }
// ]
You can map the array into the object like so:
const ages = ['32', '26', '28'];
const studentsWithAge = students.map(obj => { ...obj, age: ages[obj.id-1] });
You could create an ages array and use the index to map the value to the corresponding object.
const students = [ // Three objects, each with four properties
{
id: 1,
name: 'Mark',
profession: 'Developer',
skill: 'JavaScript'
},
{
id: 2,
name: 'Ariel',
profession: 'Developer',
skill: 'HTML'
},
{
id: 3,
name: 'Jason',
profession: 'Designer',
skill: 'CSS'
},
];
const ages = [32, 26, 28];
const result = students.map((s, i) => {
return { ...s, age: ages[i] }
});
console.log(result);
Your code is true, another way to add ages by the id is the following code. Just use ids as object key and age as value.
The following code check if id exists in the ages const then add it to the studentsWithAge. It works exactly like your code.
const ages = {1: '32', 2: '26', 3: '28'};
const studentsWithAge = students.map(obj => {
if(ages[obj.id]) obj.age = ages[obj.id];
return obj;
});
But if you're sure all ids have age value simpler code like this could be used:
const ages = {1: '32', 2: '26', 3: '28'};
const studentsWithAge = students.map(obj => ({...obj, age: ages[obj.id]}));
The solution depends on how you store the ages data. Here's an example if you keep the ages data in an array of objects, just like you keep the students data.
This approach is easily extended, you can add any other fields related to the student to the object.
students = [
{id: 1,name: 'Mark',profession: 'Developer',skill: 'JavaScript'},
{id: 2,name: 'Ariel',profession: 'Developer',skill: 'HTML'},
{id: 3,name: 'Jason',profession: 'Designer',skill: 'CSS'}];
extraInfo = [{id: 1, age:32}, {id:2, age: 26}, {id:3, age: 33}];
const result = students.map((s)=>
({ ...s, ...extraInfo.find((a) => a.id === s.id) })
);
console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}
I am trying to merge in an array to an existing array by a key (id). Is there any easy way to do this?
For example:
people = [{id: 1, name: 'John Doe'}, {id: 2, name: 'Jane Doe'}];
places = [{id: 1, state: 'CA'}, {id: 2, state: 'AK'}];
// expected output I want is
result = [{id: 1, name: 'John Doe', places: {id: 1, state: 'CA'}}, {id: 2, name: 'Jane Doe', places: {id: 2, state: 'AK}'}}];
How can I get places property id to map into people id so basically the ID's match up and they keys are carried in?
Here is the JS way to implement the scenario :
const people = [{id: 1, name: 'John Doe'}, {id: 2, name: 'Jane Doe'}];
const places = [{id: 1, state: 'CA'}, {id: 2, state: 'AK'}];
const result = people.map(ppl => {
ppl.places = places.find(plc => plc.id === ppl.id)
return ppl;
})
console.log(result)
// ES6 way
let res = people.map(obj => {
let data = places.find(item => item.id === obj.id);
return {...obj, places: data}
});
console.log('ES6 way ......',res)
I want to edit JavaScript object.
I have an JavaScript object like this
data_without_id = [
0: {id: 1, name: "Mary", age: null}
1: {id: 2, name: "Bob", age: 33}
2: {id: 1, name: "Kelly", age: 40}
]
I want to convert this object into this
data_without_id = [
0: {id: 1, name: "Kelly", age: 40}
1: {id: 2, name: "Bob", age: 33}
]
What I need to do is:
Group by id
Get latest value.
I tried using Array.prototype.reduce(), but I can't get the result I need...
Using the function reduce would be as follow:
The function reduce for grouping and the function Object.values for extracting the values.
let data_without_id = [ { id: 1, name: "Mary", age: null }, { id: 2, name: "Bob", age: 33 }, { id: 1, name: "Kelly", age: 40 }],
result = Object.values(data_without_id.reduce((a, {id, name, age}) => {
a[id] = {id, name, age};
return a;
}, Object.create(null)));
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could use .reduce by making the accumulator an object that has keys of the id. This way you can overwrite any previously seen objects which had the same id, and then use Object.values to get your array of objects:
const data_without_id = [{id: 1, name: "Mary", age: null}, {id: 2, name: "Bob", age: 33}, {id: 1, name: "Kelly", age: 40}],
res = Object.values(data_without_id.reduce((acc, obj) =>
(acc[obj.id] = obj, acc)
, {}));
console.log(res);
You could just simply use a for/of loop to create a copy of the data where the last object with a particular id will always be the object returned in the output data. This avoids the "grouping" part of the code but still returns the correct data.
const data_without_id = [
{ id: 1, name: "Mary", age: null },
{ id: 2, name: "Bob", age: 33 },
{ id: 1, name: "Kelly", age: 40 }
];
function lastId(arr) {
const out = [];
for (let obj of arr) {
// If you don't create a copy of each object the returned
// data will simply be contain _references_ to the original
// data. Changes in the original data will be reflected
// in the returned data
out[obj.id - 1] = { ...obj };
}
return out;
}
const lastIds = lastId(data_without_id);
console.log(lastIds);