I have a object like this
users = {
user1:{name: bob,
age:23},
user2:{name:rob,
age:24},
user3:{name:jay,
age:30}}
How to convert this object into an array like [user1:{name: bob,age:23},user2{name:rob,age:24},user3:{name:jay,
age:30}]
Simple, map the Object.keys array of your object to the array you want. I added in the object key as the "id" field.
const users = {
user1:{name: 'bob',
age:23},
user2:{name:'rob',
age:24},
user3:{name:'jay',
age:30}};
const arr = Object.keys(users).map(key => ({id: key, ...users[key]}));
console.log(arr);
the map solution is more up to date but sometimes old vanilla js is easier to understand
const users = {user1:{name:'bob',age:23},user2:{name:'rob',age:24},user3:{name:'jay',age:30}};
var myArray=[];
for(let i =1;i<4;i++){
var user={['user'+i]:users['user'+i]} //create your object
myArray.push(user); //add it to array
}
console.log(myArray[0]['user1']) // remember arrays are indexed []
console.log(myArray[1]['user2'])
console.log(myArray[2]['user3'])
console.log(myArray);
.as-console-wrapper{min-height:100%;})
Related
I have an array like this:
const data = [{
color:"red",
to:1,
from:2,
opacity:12
}]
I want something like this:
const converted = [{from:2}, {to:1}, {opacity:12}]
What I am trying is:
const mappedData = data.map(({from,to,opacity}) => ({from:from},{to:to},{opacity:opacity}))
but this is not working.
So you can loop through the array and for each object we can get the keys of the objects in the array and use a map to transform them to our desired output, Then the output will return an array, but we can use flatMap which will flatten the arrays returned into a single array of objects!
Thanks pilchard for teaching about flatMap!
const data = [{
color:"red",
to:1,
from:2,
opacity:12
}]
const arr = data.flatMap(x => Object.keys(x).map(data => ({[data]: x[data]})))
console.log(arr);
I have to following array:
var arr1 = [
[{n:"0.1",m:"m.0",other:"eg1"}],
[{n:"1.1",m:"m.1",other:"eg2"}],
[{n:"2.1",m:"m.2",other:"eg3"}]
];
And I would like to convert it to an array of arrays, as follows:
var arr1 = [
["0.1","0"],
["1.1","1"],
["2.1","2"]
];
I would like to convert to the other array only a few properties, not all of them.
Any idea how I can do this?
PS: I was using flatMap from another post but it does not work as it does not exist in Edge.
Assuming that the second value in each subarray is coming from the number after the period from the m key, you could use the map function to accomplish this:
var arr1 = [
[{n:"0.1",m:"m.0",other:"eg1"}],
[{n:"1.1",m:"m.1",other:"eg2"}],
[{n:"2.1",m:"m.2",other:"eg3"}]
];
var newArray = arr1.map(x => [x[0].n, x[0].m.split('.')[1]]);
console.log(newArray);
For next time you have to put your attempts.
this is the solution for your problem
var arr1 = [
[{n:"0.1",m:"m.0",other:"eg1"}],
[{n:"1.1",m:"m.1",other:"eg2"}],
[{n:"2.1",m:"m.2",other:"eg3"}]
];
arr1 = arr1.map(currentArray=>{
const item = currentArray.shift();
return [item.n,item.m.replace( /^\D+/g, '')]
});
I was just working with JavaScript objects and found this which i cant figure out . I created an array with few values and trying to convert that array into object using spread and new in JavaScript but for my surprise only the first value in the array is been put into the object with its type .
I have no need what exactly is happening in background
let array = [1970,1,1]
let object = new Object(array)
console.log(object)
Output :
NumberĀ {1970}
I was expecting {1970 , 1 , 1} object but actual output is
NumberĀ {1970}
to convert array to object use Object.assign
Object.assign({},[1970,1,1])
or you can populate the object with the array elements
let array = [1970,1,1];
var obj = new Object();
Array.prototype.push.apply(obj, array);
console.log(obj);
The closest thing you could do is:
const object = {...array}
Which will give you the output:
{0: 1970, 1:1, 2:1}
You can try with Object.assign()
let array = [1970,1,1];
let object = Object.assign({}, array);
console.log(object);
It works in the Chrome (Version 75).
Check the following code, if in case you are expecting the following behavior.
CODE:
let array = [1970,1,1];
let obj = {}, i = 0;
for(var element in array) obj[i++] = array[element];
console.log(obj);
I have an Object array that looks like the following:
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
And I want to convert it to look like this:
var newArray = [
1, 2, 3
]
So it's basically taking the object array, extracting the id's out of the objects, and creating a new array that contains the id's that were extracted. Is there a way to do this in one line? Even better if a new array doesn't have to get created and array is just updated.
var test ="sai";
var array = [
{'id':1,'description':test},
{'id':2,'description':test},
{'id':3,'description':test}
]
console.log(array.map(function(obj){return obj.id}))
iterate the array using foreach and populate newArray
var newArray = [];
array.forEach(funtion(element){
newArray.push(element.id);
});
console.log( newArray );
array.map(function (item) {
return item["id"];
}
If you'd like to have anew instance of the mapped array:
var newarray = [];
array.forEach(function (item) {
newarray.push(item["id"]);
}
array.map(function(element) {return element.id})
OP Requirement: better if array is just updated
array = array.map(function(element) {return element.id})
How can I get the value of an object with an unknown single key?
Example:
var obj = {dbm: -45}
I want to get the -45 value without knowing its key.
I know that I can loop over the object keys (which is always one).
for (var key in objects) {
var value = objects[key];
}
But I would like to know if there is a cleaner solution for this?
Object.keys might be a solution:
Object.keys({ dbm: -45}); // ["dbm"]
The differences between for-in and Object.keys is that Object.keys returns all own key names and for-in can be used to iterate over all own and inherited key names of an object.
As James Brierley commented below you can assign an unknown property of an object in this fashion:
var obj = { dbm:-45 };
var unkownKey = Object.keys(obj)[0];
obj[unkownKey] = 52;
But you have to keep in mind that assigning a property that Object.keys returns key name in some order of might be error-prone.
There's a new option now: Object.values. So if you know the object will have just one property:
const array = Object.values(obj)[0];
Live Example:
const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
const obj = JSON.parse(json);
const array = Object.values(obj)[0];
console.log(array);
If you need to know the name of the property as well, there's Object.entries and destructuring:
const [name, array] = Object.entries(obj)[0];
Live Example:
const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
const obj = JSON.parse(json);
const [name, array] = Object.entries(obj)[0];
console.log(name);
console.log(array);