The default object is:
var employee = {
'name': 'Hermione',
'salary': 1000
};
My question is, how to copy that to another object with this formatting?
var employee = {
'Hermione': 1000
};
I've tried:
for (var prop in employee) {
console.log(prop, employee[prop]); // 'name' 'Hermione'
// what next?
}
UPDATE:
var employees = [];
employees.push({ 'name': 'name1', 'salary': 1000 });
employees.push({ 'name': 'name2', 'salary': 2000 });
employees.push({ 'name': 'name3', 'salary': 3000 });
What I want to achieve:
var employees = [
{'name1': 1000},
{'name2': 2000},
{'name3': 3000}
];
Do you have an array of those objects?
For single object the case is rather simple:
var employee2 = {};
employee2[employee['name']] = employee['salary'];
or for modern browsers:
var employee2 = {
[employee['name']]: employee['salary']
};
update
for array of objects:
var employees = [
{ name: 'name1', salary: 1000 },
{ name: 'name2', salary: 2000 },
{ name: 'name3', salary: 3000 }
];
var employees2 = employees.map(employee => ({[employee.name]: employee.salary}));
console.dir(employees2);
for older browsers:
var employees2 = employees.map(function(employee) {
var result = {};
result[employee['name']] = employee['salary'];
return result;
});
You should use Array.prototype.filter Or Array.prototype.map
var employees = [];
employees.push({ 'name': 'n1', 'salary': 1000 });
employees.push({ 'name': 'n2', 'salary': 2000 });
employees.push({ 'name': 'n3', 'salary': 3000 });
var reduced = employees
.reduce((res, val) => {
res[val.name] = val.salary;
return res;
}, Object.create(null))
;
console.log('reduced', reduced);
var mapped = employees
.map(i => ({[i.name] : i.salary}))
;
console.log('mapped', mapped);
newobj = {}; newobj[oldObj.name] = oldObj.salary
Related
I already have an object witch has two arrays:
const services = {
iconAndLink: [
'Icon1',
'Icon2',
'Icon3',
],
name: [
'Name1',
'Name2',
'Name3',
],
};
I looked into Object.assign(), array.reduce(), map etc... and can't seem to find a decent answer here that merges these two.
For final result I need:
services = [
{
icon: 'Icon1',
name: 'Name1'
},
{
icon: 'Icon2',
name: 'Name2'
},
{
icon: 'Icon3',
name: 'Name3'
},
]
Note that I need to have the icon and name keys.
Is this even possible in js?
This should work
const services = {
iconAndLink: ["Icon1", "Icon2", "Icon3"],
name: ["Name1", "Name2", "Name3"],
};
let result = services.iconAndLink.map(function (icon, index) {
return { icon: services.iconAndLink[index], name: services.name[index] };
});
console.log(result);
Make sure both arrays same the same length and both are ordered
A simple forEach loop using index would do the trick
const services = {
iconAndLink: [
'Icon1',
'Icon2',
'Icon3',
],
name: [
'Name1',
'Name2',
'Name3',
],
};
let newarray = [];
services.iconAndLink.forEach((el, index) => newarray.push({
icon: el,
name: services.name[index]
})
);
console.log(newarray)
const services={iconAndLink:["Icon1","Icon2","Icon3"],name:["Name1","Name2","Name3"]};
const res = services.name.map((e, i) => ({
icon: e,
name: services.iconAndLink[i]
}))
console.log(res)
Assuming the arrays are of the same size, you can do:
const services = { iconAndLink: [ 'Icon1', 'Icon2', 'Icon3', ], name: [ 'Name1', 'Name2', 'Name3', ], };
const newArr = [];
for (let i = 0; i < services.iconAndLink.length; i++) {
newArr.push({icon: services.iconAndLink[i], name: services.name[i]})
}
console.log(newArr)
I have an array of objects:
var test = [{name: 'lorem', age: 20, color:'red'}, {name: 'lorem', weight: 1, height:5} , {name: 'hello', ipsum : 'dolor'}]
I would like to merge and group them. Expected result is:
var test = [{name: 'lorem', age : 20, color: 'red', weight : 1, height : 5}, {name: 'hello', ipsum : 'dolor'}]
Solution can be in vanilla, lodash or JQuery ...
EDIT:
Sorry guys, I forgot to say that it has to be written in ES5
EDIT:
I almost rewrote gorak's propostion to ES5. I tried _.clone to avoid using spread opearator but it doesn't work
var r = _.values(_.reduce(test,function (acc, e) {
acc[e.name] = {...(acc[e.name] || {}), ...e}; // this line is still in ES6
return acc;
},{}));
You can make use of reduce and take Object.values. Here is a working example:
var test = [{name: 'lorem', age: 20, color:'red'}, {name: 'lorem', weight: 1, height:5} , {name: 'hello', ipsum : 'dolor'}];
var result = Object.values(test.reduce((acc, e)=>{
acc[e.name] = {...(acc[e.name] || {}), ...e};
return acc;
},{}));
console.log(result);
Also another approach could be to take Set values(unique names) and then use Object.assign to merge the filtered array. Give this a try:
var test = [{name: 'lorem', age: 20, color:'red'}, {name: 'lorem', weight: 1, height:5} , {name: 'hello', ipsum : 'dolor'}];
var result = [...new Set(test.map(({name})=>name))].map(n=>Object.assign(...test.filter(p=>p.name==n)));
console.log(result);
You can use below method
var test = [
{ name: 'lorem', age: 20, color: 'red' },
{ name: 'lorem', weight: 1, height: 5 },
{ name: 'hello', ipsum: 'dolor' },
]
const finalResult = test.reduce((result, obj) => {
if (result[obj.name]) {
result[obj.name] = {
...result[obj.name],
...obj,
}
} else {
result[obj.name] = { ...obj }
}
return result
}, {})
console.log(Object.values(finalResult))
This function will do the trick!
(The name is placed at the bottom of each object, but that doesn't matter)
(pure JS)
function mergeList(list) {
var temp = {};
list.forEach(elem => {
var name = elem.name;
delete elem.name;
temp[name] = {
...temp[name],
...elem
}
});
var merged = [];
Object.keys(temp).forEach(key => {
var object = temp[key];
object.name = key;
merged.push(object);
});
return merged;
}
var test = [{
name: 'lorem',
age: 20,
color: 'red'
}, {
name: 'lorem',
weight: 1,
height: 5
}, {
name: 'hello',
ipsum: 'dolor'
}];
console.log(mergeList(test));
I have some data to be combined in one document in the mongoDB.
I have two arrays
const users = ['Anna', 'Jack', 'Paul', 'Elena']
const additionalData = ['data1', 'data2', 'data3', 'data4', 'data5']
for(const i of users){
const user = {
username: i.username
};
for(const key of additionalData){
user.keyword = key
}
await User.create(model)
}
[
{
username: 'Anna',
keyword: 'data1'
},
{
username: 'Jack',
keyword: 'data2'
},
{
username: 'Paul',
keyword: 'data3'
},
{
username: 'Elena',
keyword: 'data4'
}
]
I need to combine those arrays in the one document
Try this, You just need to loop through users and get data from additionalData with the current index. You can achieve this in 2 ways
Native Way
const users = ['Anna', 'Jack', 'Paul', 'Elena'];
const additionalData = ['data1', 'data2', 'data3', 'data4', 'data5'];
const newArray = [];
for (let i = 0; i < users.length; i += 1) {
const user = users[i];
const obj = { userName: user, keyword: additionalData[i] || null };
newArray.push(obj);
}
console.log(newArray);
ES6 Way
const users = ['Anna', 'Jack', 'Paul', 'Elena'];
const additionalData = ['data1', 'data2', 'data3', 'data4', 'data5'];
const result = users.map((r, i) => {
const obj = { userName: r, keyword: additionalData[i] || null };
return obj;
});
console.log(result)
// Users and additionalData array
const users = ['Anna', 'Jack', 'Paul', 'Elena'];
const additionalData = ['data1', 'data2', 'data3', 'data4', 'data5'];
// Merge them with this
$.merge( $.merge( [], users ), additionalData );
I'm new to JS and experimenting the things. I have following object:
var data = {'name': 'john', 'old': 18, 'place': 'USA'}
How can I switch the keys of this object with the following array?
var array = ['First Name', 'age', 'country']
To look following:
{'First Name': 'john', 'age': 18, 'country': 'USA'}
The only way to rename a key of an object is to assign the value of the old key to the new key and then delete the old key
Object[ new_key ] = Object[ old_key ];
delete Object[ old_key ];
Another way is to create a completely new object (with the new keys), assign the values to the new keys and then delete the old object.
var array = ['First Name', 'age', 'country'];
var data = {'name': 'john', 'old': 18, 'place': 'USA'};
var keys = Object.keys(data);
var newData = {};
for (var a in array) {
//using new obj
newData[array[a]] = data[keys[a]];
//editing same obj
data[array[a]] = data[keys[a]];
delete data[keys[a]];
}
console.log(data);
console.log(newData);
var array = ['First Name', 'age', 'country'];
var list = [
{ 'name': 'john 1', 'old': 18, 'place': 'USA' },
{ 'name': 'john 2', 'old': 19, 'place': 'USB' },
{ 'name': 'john 3', 'old': 20, 'place': 'USC' },
];
var newList = [];
for (var item in list) {
var newData = {};
for (var a in array) {
newData[array[a]] = list[item][Object.keys(list[item])[a]];
}
newList.push(newData);
}
console.log(newList);
You can use Object.assign(), Object.entries(), .map(), spread element and computed properties to assign the property name to a new object having value to to current index of property, value within iteration, set identifier for original object to result of Object.assign() call
let array = ['First Name', 'age', 'country']
let data = {'name': 'john', 'old': 18, 'place': 'USA'}
data = Object.assign({}, ...Object.entries(data)
.map(([, prop], index) => ({[array[index]]: prop})));
console.log(data);
Rather than switching the object keys; which cannot be done and you'd have to delete keys and add the new one, you could simply create a new object with the desired keys:
var data2 = {};
data2['First Name'] = data.name;
data2.age = data.old;
data2country = data.place;
You could use an object with the replacement keys and iterate it for changing the keys.
var data = { name: 'john', old: 18, place: 'USA' },
newKeys = { name: 'First Name', old: 'age', place: 'country' };
Object.keys(newKeys).forEach(function (k) {
data[newKeys[k]] = data[k];
delete data[k];
});
console.log(data);
var data = {'name': 'john', 'old': 18, 'place': 'USA'}
var ary = ['First Name', 'age', 'country']
// create key-value pairs array
var obj_entries = Object.entries(data)
var new_data =ary.reduce((acc, value, idx)=>{
acc[value]=obj_entries[idx][1];
return acc;
}, {})
console.log(new_data)
Maybe a functional approach
I have two arrays of objects that I'm trying to merge
var status = [
{name: 'status_1', pk:1 }, {name: 'status_2', pk:2 }
]
var to_be_merged = [
{'status_pk': 1, 'value': 10}, {'status_pk': 2, value: 20}
]
desired result
var status = [
{name:'status_1',
pk:1,
to_be_merged:{
'status_pk': 1, 'value': 10
}, {
name: 'status_2',
pk:2,
to_be_merged: {
'status_pk': 2, value: 20}
},
]
I've tried using nested _.each but I lost the scope of the above each
_.each(status, function(status) {
var objs = _.each(to_be_merged, function(x) {
if (x.status_pk == status.pk) {
// do something
}
})
})
map should help you. Combine it with merge and where to merge the two items together.
_.each(status, function(item) {
item['to_be_merged'] = _.find(to_be_merged, function(other) {
return other['status_pk'] === item.pk;
});
})
This is slightly more verbose, but so you can see what's going on:
var stat = {
s: [
{name: 'status_1', pk:1 }, {name: 'status_2', pk:2 }
],
m: [
{'status_pk': 1, 'value': 10}, {'status_pk': 2, value: 20}
]}
var merged = []
_(stat.s).each(function(s){
_(stat.m).each(function(m){
var obj = {};
if(s.pk == m.status_pk){
obj.name = s.name;
obj.pk = s.pk;
obj.to_be_meged = m
merged.push(obj);
}
})
})
console.log(merged);
DEMO