ES6 Object Spread concat - javascript

I am new to object spread. I just knew object spread can be used to concat arrays . In below example i am concatenating variable a and address key. I want to know can we add address key value to each object of a array and get output as Required Output in code.
Can any one help me good reference to learn more on Object Spread.
var a = [{
'name':'jay',
age: 31
},
{
'name':'jay1',
age: 30
},
{
'name':'jay2',
age: 29
}];
var b = {...a, ...{address: 'add'}};
//b output
{name: "jay", age: 31}
{name: "jay1", age: 30}
{name: "jay2", age: 29}
address:"add"
// Required Output
{name: "jay", age: 31, address:"add"}
{name: "jay1", age: 30, address:"add"}
{name: "jay2", age: 29, address:"add"}

{ value:1, ...a, ...b, value:3 }
equals:
Object.assign({value:1}, a, b, {value:3})
In your case you need to do that for every element of your array:
const result = a.map(obj => ({...obj, address:"add"}));

Related

How do I convert an array of objects to an object of objects? [duplicate]

This question already has answers here:
Convert Array to Object
(46 answers)
Closed 26 days ago.
For example, I have the following array of objects:
[{id:1, name: Hana, age: 30}, {id:2, name: Sana, age: 20}, {id:3, name: Kana, age: 30}]
I want to convert it to an object of objects as following:
{0:{id:1, name: Hana, age: 30}, 1:{id:2, name: Sana, age: 20}, 2:{id:3, name: Kana, age: 30}}
Using Object's pre built method assign you can achieve this.
Object.assign({}, yourObject);
No need to iterate through the Array unnecessary.
You can easily achieve the result, using a simple map function and store the result in an object as a key:value pair
const data = [{id:1, name: 'Hana', age: 30}, {id:2, name: 'Sana', age: 20}, {id:3, name: 'Kana', age: 30}]
const resultObj = {}
data.map((obj,index) => resultObj[index] = obj)
console.log(resultObj)
You can map that array and get its unique value (in this case i have taken id as key) then map it according you want to display array.
Here is an example to do that.
var arr = [{
id: 1,
name: 'Hana',
age: 30
}, {
id: 2,
name: 'Sana',
age: 20
}, {
id: 3,
name: 'Kana',
age: 30
}]
var mapped = arr.map(item => ({
[item.id]: item
}));
var newObj = Object.assign({}, ...mapped);
console.log(newObj);

How can I convert an array of objects into an array of objects with the same values but with modified keys?

I have an array with objects and want to convert this to an array containing the same values but with different key names. (JavaScript)
For example, an array of
[{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}]
becomes
[{identification: "Bob", years: 50, person: true}, {identification: "Jerry", years: 20, person: true}]
Using the Map function works perfectly here.
const people = [
{name: "Bob", age: 50, person: true},
{name: "Jerry", age: 20, person: true}
];
const formatted = people.map((person) => ({
identification: person.name,
years: person.age,
person: person.person
});
This should work for this problem.
I think that you may use the map method this method returns and array with the same length as the one you are mapping:
const array = [{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}];
let newKeysArray = array.map( a => {
let obj = {
identification: person.name,
years: person.age,
person: person.person
};
return obj
} );
So inside the map you are assigning the values that you need to a new object and return the object as the mapped item.
Just in case you prefer to modify the objects in place, you can make use of a strategy by nverba here:
let rows = [
{name: "Bob", age: 50, person: true},
{name: "Jerry", age: 20, person: true}
];
let keyMaps = [
['name', 'identification'],
['age', 'years'],
];
for(let keyMap of keyMaps)
for(let row of rows)
delete Object.assign(row, {[keyMap[1]]: row[keyMap[0]] })[keyMap[0]];
console.log(rows);
keyMap[1] is the new key. keyMap[0] is the old key. Object.assign takes the value of the old key and places it in the new key. The delete keyword is confusing, but it doesn't apply to row as a whole. It's only deleting the old key.

JavaScript: Comparing two objects

I want to compare two objects to make a new object.
original = [
{id: "A1", name: "Nick", age: 20, country: 'JP', code: 'PHP'}
]
edited = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", name: "Nick", age: 25, country: 'US', code: 'PHP'}
]
Compare two objects ('original' and 'edited')
If 'id' is set, compare the same ids' data, and take the data from 'edited', and get ONLY the 'id' and the data that is edited.
If 'id' is not set keep the whole data
The final object I want is like below;
final = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", age: 25, country: 'US'}
]
I've been trying this using filter, but I can't get desired result...
Try with Array#reduce .
Updated with all key pair match
Validate the edited array id value is available in original array using Array#map and indexOf function
If not push entire object to new array
First recreate the original array to object format like {key:[value]}
Then match each key value pair match or not with forEach inside the reduce function
var original = [{id: "A1", name: "Nick", age: 20, country: 'JP'}];
var edited = [{name: "Mike", age: 30, country: 'US'},{id: "A1", name: "Nick", age: 25, country: 'US'}];
var ids_org = Object.keys(original[0]).reduce((a,b,c)=> (a[b]=original.map(a=> a[b]),a),{});
var res = edited.reduce((a, b) => {
if (b.id) {
Object.keys(b).forEach(i=>{
if(ids_org[i].indexOf(b[i]) > -1 && i != 'id')
delete b[i];
})
a.push(b);
} else {
a.push(b);
}
return a;
}, []);
console.log(res)
use de structuring to extract out id from the object.
use lodash isEqual method to compare and later add back the id to the object.

change a prop in list of object in ramda.js

I have an array of object in JSON and want to change one value's properties.
for example assume I have a key field which is unique and amount, name props.
my approach is to find an object in the list with findIndex or map then remove it and make a new object and push to it. is this good way?
can recommend better approach or functions?
Lenses might be the canonical way to deal with this, although Ramda has a number of alternatives.
const people = [
{id: 1, name: 'fred', age: 28},
{id: 2, name: 'wilma', age: 25},
{id: 3, name: 'barney', age: 27},
{id: 4, name: 'betty', age: 29},
]
const personIdx = name => findIndex(propEq('name', name), people)
const ageLens = idx => lensPath([idx, 'age'])
const wLens = ageLens(personIdx('wilma'))
const newPeople = over(wLens, age => age + 1, people)
//=> [
// {id: 1, name: 'fred', age: 28},
// {id: 2, name: 'wilma', age: 26},
// {id: 3, name: 'barney', age: 27},
// {id: 4, name: 'betty', age: 29},
// ]
Note that although newPeople is a brand new object, it shares as much as it can with the existing people. For instance, newPeople[3] === people[3] //=> true.
Also note that as well as adjusting a parameter with this lens using over, we could simply fetch the value using view:
view(wLens, people) //=> 25
Or we could set it to a fixed value with set:
set(wLens, 42, people) //=> new version of `people` with wilma's age at 42
Finally, note that lenses compose. We could have also written this:
const ageLens = idx => compose(lensIndex(idx), lensProp('age')).
Lens composition can be very powerful.
You can see this in action on the Rand REPL.
Something like this maybe?
var org =
[
{name:"one",age:1}
,{name:"two",age:2}
]
;
var newArray =
org
.map(
(x,index)=>
index === 1
?Object.assign(
{}
,x
,{name:"new name"}
)
:x
)
;

Merge Array of Objects

I need to merge arrays of objects in browserside javascript like this:
[
{name: "john", age: 10},
{name: "doe", age: 14}
]
--> new data arrives
[
{name: "pete", age: 88},
{name: "larry", age: 42}
]
should become
[
{name: "john", age: 10},
{name: "doe", age: 14},
{name: "pete", age: 88},
{name: "larry", age: 42}
]
Well thats simplified the arrays will contain hundreds of larger objects. Therefore I need a performant solution.
Thanks in advance yours skeec
It seems you can just use .push() or .concat() to combine the two arrays. It does not matter what is in the arrays as the array operators just work on the elements of the array abstractly without knowing what's in them.
Here's a solution that adds the new array onto the existing one:
var data = [
{name: "john", age: 10},
{name: "doe", age: 14}
];
var newInfo = [
{name: "pete", age: 88},
{name: "larry", age: 42}
]
data = data.concat(newInfo);
Or, if you really want to keep the original array (not create a new one), you can add the new array onto the end of the original array like this:
data.push.apply(data, newInfo);
Assuming you don't need anything other than just concatenating the 2 arrays, it's supremely simple, since arrays have a method for concatenation already.
var arr1 = [
{name: "pete", age: 88},
{name: "larry", age: 42}
];
var arr2 = [
{name: "pete", age: 88},
{name: "larry", age: 42}
];
var concatArr = arr1.concat(arr2);
MDN Page on Array.prototype.concat
var arr3 = [];
for(var i in arr1){
var shared = false;
for (var j in arr2)
if (arr2[j].name == arr1[i].name) {
shared = true;
break;
}
if(!shared) arr3.push(arr1[i])
}
arr3 = arr3.concat(arr2);
You can use loadash for that:
Something like this:
var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
console.log(other);
// → [1, 2, 3, [4]]
console.log(array);
// → [1]
Or for Json you can use extend like this:
lodash.extend({}, mergeInto, toMerge)

Categories

Resources