Mapping keys into objects with Javascript [duplicate] - javascript

This question already has answers here:
How to transpose a javascript object into a key/value array
(11 answers)
Closed 8 months ago.
This is the object I have:
years = {1924:2, 1934: 10, 2010: 4}
I would like to transform this into:
years = [{year: 1924, items: 2}, {year: 1934, items: 10}, {year: 2010, items: 4}]
This is the code I came up with so far (which obviously doesn't work):
var years2 = {};
for (var i = 0; i < years.length; ++i) {
years2.push({ years: [$key] })
};
I am stuggling to find the right way to access the unnamed keys and map these into their own objects.
(I am still learning JS and I know this is basics, but somehow cannot get my head around it.. )

You can create key value pairs from the object with Object entries and map them to new array
const years = {1924:2, 1934: 10, 2010: 4}
const ans = Object.entries(years).map(([key,value]) => {
return {year: key, items: value}
})
console.log(ans);

You can get entries, then convert to object with map
const years = {1924:2, 1934: 10, 2010: 4}
const result = Object.entries(years).map(([year, items]) => ({year: year, items: items}))
console.log(result)

Related

Sort objects inside array [duplicate]

This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Closed 2 years ago.
I have an array of object and want to reorder objects inside array Is there any way to do that?
var obj = [ {start: 12, end: 14}, {start: 2, end:8}]
I should check if start date of first object is greater than second object's start date and change objects order, The result in this case should be =>
var obj = [ {start: 2, end:8}, {start: 12, end: 14}]
I know about sorting inside object but cant find way to reorder the whole object.
Use your expeceted property to conduct compared function
var obj = [
{ start: 12, end: 14 },
{ start: 2, end: 8 },
]
const res = obj.sort((a, b) => a.start - b.start)
console.log(res)

Angular 8 : Merging two objects in an array [duplicate]

This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
How to convert an array of objects to object with key value pairs
(6 answers)
Closed 3 years ago.
I have a couple of objects inside of an array :
array1 =[{name : "Cena", age : 44},{job : "actor", location : "USA"}]
is there a way for me to merge these two objects to get something like :
array2 =[{name : "Cena", age : 44, job : "actor", location : "USA"}]
I tried looping through the elements but it is not a good option if the object is a big one, I guess. Any good solution using typescript?
You can use Array.prototype.reduce:
const array1 = [{ name: "Cena", age: 44 }, { job: "actor", location: "USA" }];
const array2 = [array1.reduce((acc, cur) => ({ ...acc, ...cur }))];
console.log(array2);

(javascript) Get all object keys from array of objects with dynamic properties [duplicate]

This question already has answers here:
Getting JavaScript object key list
(19 answers)
Closed 5 years ago.
What's the easiest way to get object keys from array of objects.
Ex.
var obj = [{"foo": 1, "bar": 2}, {"foo": 10, "bar": 20, "baz": 30}]
// ['foo', 'bar', 'baz']
You can map everything to a single array with reduce:
obj.reduce((acc, curr) => acc.concact(Object.keys(curr)), [])
This gives you:
['foo', 'bar', 'foo', 'bar', 'baz']

How to transform an array to an object [duplicate]

This question already has answers here:
How to convert an array of objects to object with key value pairs
(7 answers)
How to convert an array of key-value tuples into an object
(14 answers)
Closed 5 years ago.
I would like to turn this:
let myArray = [ {city: "NY"}, {status: 'full'} ];
to this:
let myObj = { city: "NY", status: 'full' };
while I tried this:
let newObj = {};
for (var i = 0; i < myArray.length; i++) {
(function(x) {
newObj = Object.assign(myArray[i]);
})(i);
}
it assigns the last pair to the object
Spread the array into Object#assign:
const myArray = [ {city: "NY"}, {status: 'full'} ];
const myObj = Object.assign({}, ...myArray);
console.log(myObj);
Note: Assign into an empty object. If you omit the empty object, the 1st element of the original array will be mutated (everything will be merged into it).
You could also use Array.reduce() which will give you more fine grain control:
const myArray = [
{ city: 'NY', color: 'blue', rodents: { small: false, medium: false, large: true } },
{ status: 'full', color: 'red' },
{ sandwich: 'flavourful' },
]
// item is each object in your array
const reduced = myArray.reduce((newObj, item) => {
// existing props will be overwritten by newer object entries in the array
// this example is same as Object.assign spread with right to left precedence,
// until you want more custom logic
Object.keys(item).forEach((key) => { newObj[key] = item[key] })
return newObj
}, {})
console.log(reduced)
// you will see `red` overwrite `blue`
EDIT: after examining this answer after a year, I note that it isn't optimized at all for ability to deep clone or deep merge. I recommend studying those aspects closer and to be careful of copying or breaking references if you are working immutably.
There is no issue with this in the above example because all values are primitives.
I would tend to agree with Ori that your question seems to be about creating an indexed object which isn't usually a good plan, but if its necessary to key your object with numbers you can do it like this:
let newObj = {};
myArray.forEach((val, index) => { newObj[index] = val });
let myArray = [ {city: "NY"}, {status: 'full'} ];
let newObj = myArray.reduce((acc, curr) => {
Object.keys(curr).forEach(val => {
acc[val] = curr[val]
})
return acc
}, {})
console.log(newObj)
This syntax is supported in IE according to caniuse.com

Store an Array in sessionstorageItem [duplicate]

This question already has answers here:
How to store objects in HTML5 localStorage/sessionStorage
(24 answers)
Closed 7 years ago.
I have the following javascript objects. I would like to store the following array on sessionstorageItem, but it was giving me error. How can I able to store an array in sessionstorageItem?
data=[];
data[0] = [{
"num": 29,
"ser": 1,
}, {
"num": 44,
"ser": 2,
}]
data[1]=[{
"num": 10,
"ser": 3,
}]
allData = data.reduce(function (a, b) { return a.concat(b) });
// the following line gives me an error
var MDData=JSON.parse(sessionStorage.MDData);
if (MDData!==null) {console.log("Hello")}
sessionStorage.setItem('MyData', JSON.stringify(allData));
webStorage can only store strings. So you need to stringify your data.
sessionStorage.setItem('Myata', JSON.stringify(allData));
To retrieve it back you can do:
JSON.parse(sessionStorage.Myata);
you have and extra ')' in "sessionStorage.setItem('Myata', sell.allData));"

Categories