This question already has answers here:
How to add index values of array in object to a key
(7 answers)
Closed 4 months ago.
I've a data like this.
const arr = [
{name:'john'},
{name:'jeff'},
{name:'bob'},
{name:'peter'},
]
arr.forEach((v,i,a)=>{
console.log(v)
})
And I want to transfer to
arr = [{id:1,name:john},{id:2,name:jeff},{id:3,name:bob},{id:4,name:peter}]
I want to add id to every object in array.
How to solves this, Thank you.
const arr = [
{name:'john'},
{name:'jeff'},
{name:'bob'},
{name:'peter'},
]
arr.forEach((v,i,a)=>{
v.id = i + 1
})
console.log(arr)
Try this :
const arr = [
{name:'john'},
{name:'jeff'},
{name:'bob'},
{name:'peter'},
];
const res = arr.map((obj, index) => {
return {
...obj,
id: index + 1
}
});
console.log(res);
Related
This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 5 months ago.
I need to combine ccAddresses and toAddresses values into just one set of array without duplication.
Expected Output
{ "newAddresses": ["john#gmail.com", "joshua#gmail.com", "jane#gmail.com", "james#gmail.com"] }
const old = [
{
"ccAddresses": ["john#gmail.com", "joshua#gmail.com"],
},
{
"ccAddresses": ["jane#gmail.com", "joshua#gmail.com"],
"toAddresses": ["jane#gmail.com", "james#gmail.com"],
}
];
const news = old.flatMap((val, index) => ({
"newAddress": val.ccAddresses
}))
console.log(news)
const res = Array.from(new Set([...old.flatMap(x => [...x.ccAddresses])]))
UPDATED(as per new author's requirement):
Array.from(new Set([...old.flatMap(x => [...x.ccAddresses].concat([...x.toAddresses || []]))]))
This question already has answers here:
Sum values of objects in array
(8 answers)
Closed 1 year ago.
In JavaScript, suppose I have:
list1=[
{name='Mark',count='3'}
{name='Harry',count='2'}
]
list2=[
{name='John',count='3'}
{name='Mark',count='1'}
]
list3=[
{name='John',count='3'}
{name='Harry',count='1'}
]
and I want an intersection of the list that adds "count" of the same "name" items
result:
listResult=[
{name='Mark',count='4'}
{name='Harry',count='3'}
{name='John',count='6'}
How would I proceed?
You could use Array.reduce to create a map of the name counts, then use Object.values to return the desired result.
We first of all concatenate the lists ([list1, list2, list2].flat()), then use .reduce to create our map keyed on item name.
const list1=[ {name:'Mark',count:'3'}, {name:'Harry',count:'2'} ]
const list2=[ {name:'John',count:'3'}, {name:'Mark',count:'1'} ]
const list3=[ {name:'John',count:'3'}, {name:'Harry',count:'1'} ]
const result = Object.values([list1, list2, list3].flat().reduce((acc, curr) => {
if (!acc[curr.name]) acc[curr.name] = { name: curr.name, count: 0};
acc[curr.name].count += (+curr.count);
return acc;
}, {}));
console.log(result)
The json above are not valid, but here i got what you wanted.
Have a look below
var list1=[
{name:'Mark',count:'3'},
{name:'Harry',count:'2'}
]
var list2=[
{name:'John',count:'3'},
{name:'Mark',count:'1'}
]
var list3=[
{name:'John',count:'3'},
{name:'Harry',count:'1'}
]
var result = [];
function counter(list){
list.forEach(x=>{
var f = result.find(a=> a.name == x.name);
if (f)
f.count=parseInt(f.count)+parseInt(x.count);
else result.push(x);
})
return result;
}
counter(list1)
counter(list2)
counter(list3)
console.log(result)
This question already has answers here:
Creating object with dynamic keys [duplicate]
(2 answers)
Closed 2 years ago.
I have this array: ["description", "asc"]
and want to turn it into this object:
{ "description": "asc" }
What's the fastest way to achieve this?
I tried
const obj = { array[0] : array[1] }
But it doesn't work because I can't seem to set the key of the object dynamically?
you can try this
const array = new Map([
["description", "asc"]
]);
const convobj = Object.fromEntries(array);
console.log(convobj)
You can do this:
let array = ["description", "asc"];
const obj = { [array[0]]: array[1] };
console.log(obj);
You can try this:
const bar = {
[array[0]]: array[1]
}
This question already has answers here:
Javascript string array to object [duplicate]
(4 answers)
JS : Convert Array of Strings to Array of Objects
(1 answer)
Convert array of strings into an array of objects
(6 answers)
Closed 3 years ago.
What is the best way to convert:
from
['firstName','lastName','gender']
to
0: {title: "firstName"}
1: {title: "lastName"}
2: {title: "gender"}
in JavaScript
You can use .map() to get the desired output:
const data = ['firstName','lastName','gender'];
const result = data.map(name => ({ title: name }));
console.log(result);
Try this code.I hope it will helps you.
var arr = ['firstName','lastName','gender']
var jsonObj = {};
for (var i = 0 ; i < arr.length; i++) {
jsonObj['title' +(i+1) ] = arr[i];
}
console.log(jsonObj)
You can simply use forEach() loop which is the easiest way:
var arr = ['firstName','lastName','gender'];
let res = [];
arr.forEach((item) => res.push({title: item}));
console.log(res);
Just to build your knowledge in Array operations you can also use reduce():
var arr = ['firstName','lastName','gender'];
let res = arr.reduce((acc, item) => {
acc.push({title: item});
return acc;
}, []);
console.log(res);
This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 4 years ago.
can someone help me with some code to splice an array and push to new array. I have an arrays
someArray = [{
name: "Kristian",
lines: "2,5,10"
}, {
name: "John",
lines: "1,19,26,96"
}, {
name: "Kristian",
lines: "2,58,160"
}, {
name: "Felix",
lines: "1,19,26,96"
}];
i want to splice where name = to Kristian and push to a new array
You can use .reduce() method along-with .splice():
let data = [
{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"},
{name:"Kristian", lines:"2,58,160"}, {name:"Felix", lines:"1,19,26,96"}
];
let result = data.reduce((r, c, i, a) => {
if(c.name = 'Kristian')
r.push(a.splice(i, 1));
return r;
}, []);
console.log(result);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use
Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Array.prototype.splice()
The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
var someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John", lines:"1,19,26,96"},{name:"Kristian", lines:"2,58,160"},{name:"Felix", lines:"1,19,26,96"}];
var res = someArray.filter((p,i) => {
if(p.name=="Kristian"){
someArray.splice(i, 1); //remove the mached object from the original array
return p;
}
});
console.log(res);
console.log('----------------');
console.log(someArray);
You could use a mixture of filter and map:
const filtered = someArray.filter(obj => obj.name !== "Kristian")
const newArray = someArray.map(obj => obj.name === "Kristian")
Filtered will remove the items whilst map will create a new array with the removed items