How to turn object with array into array? - javascript

I'm trying to turn the values of an array inside an object to a normal array.
Right now I'm doing something like this in my AJAX success function:
var obj = data
console.log(obj)
var array = Object.keys(obj)
.map(function(key) {
return obj[key];
});
console.log(array)
This is what I get in my console:
{jaar: Array(2)}
jaar: Array(2)
0: YEAR(Scan): "2020"
[[Prototype]]: Object
1: YEAR(Scan): "2021"
[[Prototype]]: Object
length: 2
[[Prototype]]: Array(0)
[[Prototype]]: Object
I want to have something simply as this
["2020", "2021"]
How can I achieve this and what am I doing wrong right now?
console.log(obj) at the start gives this output in the console:
jaar: Array(2)
0: {YEAR(Scan): '2020'}
1: {YEAR(Scan): '2021'}
length: 2
[[Prototype]]: Array(0)
[[Prototype]]: Object ```

If you have a plain object like const obj = { x: 10, y: 20 } and you want to have an array of its values, you can simply use Object.values(obj) that will return you [10, 20].
Seems like your object has more complex structure.
If you know for sure, any value of your object is a value or array, like
const obj2 = { x: 10, y: [20, 30, 40], z: [50, 60]} you can flatten it.
Object.values(obj2).flat() will return you [10, 20, 30, 40, 50, 60].
For more complex structures you need to have more complex handlers.

jaar is already an array of objects. You can simply use .map() and get the respective property value from each array element.
let ans =jaar.map(x => x['YEAR(Scan)']);

Other answer provides the must succinct code (using .map) - to make the the smallest change to your existing code, change:
You can read the YEAR(Scan) property like so:
return obj[key]["YEAR(Scan)"];
Updated code:
var obj =
[
{ "YEAR(Scan)":"2020" },
{ "YEAR(Scan)":"2021" }
]
console.log(obj)
var array = Object.keys(obj)
.map(function(key) {
return obj[key]["YEAR(Scan)"];
});
console.log(array)

Related

How i can trasform an object in an array of object?

I have this object
{
Bamboo: 7,
Eucalipto: 1,
Frassino: 2,
Ulivo: 1
}
I want to trasform this object in an array of object
[
{
plantName: Bamboo,
quantity: 7
},
{
plantName: Eucalipto,
quantity: 1
},
{
plantName: Frassino,
quantity: 2
},
{
plantName: Ulivo,
quantity: 1
},
]
What have you tried so far? Here's what I might do.
const dataObject = { Bamboo: 7, Eucalipto: 1, Frassino: 2, Ulivo: 1 };
const dataArray = Object.keys( dataObject ).map( ( key ) => {
return { 'plantName': key, 'quantity': dataObject[key] };
} );
console.log( dataArray );
You can map over the entries of the object, creating a new object with each key-value pair.
let obj = { Bamboo: 7, Eucalipto: 1, Frassino: 2, Ulivo: 1 };
let res = Object.entries(obj).map(([plantName,quantity])=>({plantName, quantity}));
console.log(res);
As you can see there are many different ways of doing this. But here are the basic steps as I learned them when I was starting out.
Create an array.
Iterate over the object.
Create a new object, and assign the key of the input object to "plantName", and the value of the input object to "quantity".
Add that new object to an array.
Here's an old-school way of achieving this:
const obj = { Bamboo: 7, Eucalipto: 1, Frassino: 2, Ulivo: 1 };
// Create an array
const arr = [];
// Iterate over the object
for (const key in obj) {
// Create a new object assigning the key
// to `plantName`, and the value to `quantity`
const newObj = {
plantName: key,
quantity: obj[key]
};
// Add the new object to the array
arr.push(newObj);
}
// Et voila!
console.log(arr);
Once you understand the basic concepts then you can start to introduce more complex methods like Object.entries, and map, but if you're just starting out with JavaScript this is probably more than enough to help you understand the process.

how i can make an array from an object if there are nested objects

I need a function that would make an array like this from an object:
let obj = {
name: 'john',
age: 25,
some: {
a: 5.5,
b: 5,
c: 'pls'
}
}
objectToArray(obj);
// Outputs: [['name', 'john'], ['age', 25], ['some', [['a',5.5], ['b', 5], ['c','pls']]]]
How exactly should I check if there is a nested object? Is the Object.entries () method a good fit?
I think we need a function that will check whether the object is passed or not, if so, it will open it and make an array of it [key, property] using the Object.entries () method, if there is also an object, then it will call itself again and for it ...
Ps: i need to use only native javascript with recursion
We can recurse like this:
Check if the object passed in is an object using instanceof.
If it is continue.
If not return whatever the value is.
Convert the object to it's entries using Object.entries.
Iterate over each [key, value] pair using Array#map.
Recursively call objectToArray on the value. (Jump to 1.)
This is what that looks like:
const obj = { name: 'john', age: 25, some: { a: 5.5, b: 5, c: 'pls', }, };
function objectToArray(obj) {
if (!(obj instanceof Object)) return obj;
return Object.entries(obj).map(([key, value]) => [key, objectToArray(value)]);
}
console.log(objectToArray(obj))

How map() and fill() work combined on a newly being created array

I have encountered similar code:
function createObj() {
return {
x: 'type1',
y: 100 };
}
const newArray = Array(4).fill("Dummy").map(createObj);
console.log(newArray);
This creates a new Array with 4 elements like below:
(4) [{…}, {…}, {…}, {…}]
0: {x: "type1", y: 100}
1: {x: "type1", y: 100}
2: {x: "type1", y: 100}
3: {x: "type1", y: 100}
length: 4
__proto__: Array(0)
I am not sure why it doesn't get populated with value I provided in fill ("Dummy").
I want to understand how this actually works.
I tweaked the code to this:
function createObj() {
return {
x: 'type1',
y: 100 };
}
const newArray = Array(4).fill("Dummy");
newArray.map(createObj);
console.log(newArray);
now the output is:
(4) ["Dummy", "Dummy", "Dummy", "Dummy"]
0: "Dummy"
1: "Dummy"
2: "Dummy"
3: "Dummy"
length: 4
__proto__: Array(0)
You can break the line of code down:
Array(4) // [empty, empty, empty, empty]
The above will create an array with four "empty" slots within it:
.fill("Dummy") // ["Dummy", "Dummy", "Dummy", "Dummy"]
For every empty slot within the array (from index 0 to the length of the array), the fill method will place the string "Dummy" in its location (as .fill will set all elements with a particular object from 0 to the length of the array). This is needed for the .map method to work (as .map() only iterates over values which exist).
.map(createObj)
will iterate through every element in your array, and convert it to a reference of the object returned by createObj. If you try and perform .map on an empty array, it will skip all empty slots, hence the need for .fill(). So, by using .map you are creating unique objects at each index.
They key difference is that map() returns an array rather than changing the original array.
In your first example const newArray = Array(4).fill("Dummy").map(createObj); the final call to map() returns a new array and assigns it to newArray.
In the second example const newArray = Array(4).fill("Dummy"); the reult of the fill() call is assigned to newArray. When map() is called, it runs, but the result is not assigned to any variable.
function createObj() {
return {
x: 'type1',
y: 100 };
}
const newArray = Array(4).fill("Dummy");
// This piece of code creates an array of length 4 filled with the text 'Dummy' in every index.
newArray.map(createObj);
console.log(newArray); // This console.log will point to newArray constant which is 3 rows above, it will not be the output of this: newArray.map(createObj)
const newThing = newArray.map(createObj);
// newThing is now what .map() does, which is to return a newly created array out of what you are passing.
console.log(newThing)
This is because you are returning an object - from the createObj function.
Remember the the map function returns a new array and the values within are the returned ones. Your Dummy data won't be useful in this case, only the size of the array.
let see the code piece by piece.
// will return [empty x 4]
Array(4);
// This is gonna fill in the array with the 'Dummy' text
// ['Dummy', 'Dummy', 'Dummy', 'Dummy']
Array(4).fill('Dummy');
This is what so understood so far when tweaked the code.
Now the map. If you return the value from the filled array you will get a new array fill in with the returned values
// the output is:
// ['Dummy', 'Dummy', 'Dummy', 'Dummy']
Array(4).fill('Dummy').map(value => value);
// BUT! remember what I wrote above about returning a // new value array fill in with the returned values.
// And in this case you are working ON THE RETURNED ARRAY FROM THE FILL FUNCTION.
//
// output:
// 0: {x: "type1", y: 100}
// 1: {x: "type1", y: 100}
// 2: {x: "type1", y: 100}
// 3: {x: "type1", y: 100}
Array(4).fill('Dummy').map(()=> ({
x: 'type1',
y: 100,
}));
Just remember that some functions like Array, fill, filter, map, flat, flatMap, reduce among others, they return a new array. So when you concat each function you are working on the returned array.
When we iterate over the map object it returns a new array (Immutable Function)
function createObj() {
return {
x: 'type1',
y: 100 };
}
const newArray = Array(4).fill("Dummy");
const result = newArray.map(createObj); //here return a new Array
console.log(result);

How to convert key-value pair object into an array of values in ES6?

I'm developing a React application where I need to convert a key-value object like this:
{
0: 'John',
1: 'Tim',
2: 'Matt'
};
To an array of just the values like this:
['John', 'Tim', 'Matt']
How do I accomplish this?
const obj = {
0: 'John',
1: 'Tim',
2: 'Matt'
};
const arr = /* ??? */;
You could use Object.values.
The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var object = { 0: 'John', 1: 'Tim', 2: 'Matt' },
array = Object.values(object);
console.log(array);
With ES6, you could use Array.from and use a callback for the values.
var object = { 0: 'John', 1: 'Tim', 2: 'Matt' },
array = Array.from(Object.keys(object), k => object[k]);
console.log(array);
You can make use of Object.values command.
According to the docs.
Object.values() returns an array whose elements are the enumerable
property values found on the object. The ordering of the properties is
the same as that given by looping over the property values of the
object manually
Although it is an ES2017 solution but since you are using react, you can include stage-0 as a preset for babel and access this functionality
var data ={
0: 'John',
1: 'Tim',
2: 'Matt'
};
var newdata = Object.values(data);
console.log(newdata);
there are other methods like Object.keys which gives you all the keys as an array and Object.entries method returns an array of a given object's own enumerable property [key, value] pairs which might also be useful to you
const obj = {
0: 'John',
1: 'Tim',
2: 'Matt'
};
const arr = [];
for(let key in obj){
arr.push(obj[key]);
}
While you have numerical keys and in an order without gaps, you could use Object.assign with an array as target and the given object as source.
var object = { 0: 'John', 1: 'Tim', 2: 'Matt' },
array = Object.assign([], object);
console.log(array);
This is commonly used one:
const obj={
1:'Azamat',
2: 'Kanybek',
3: 'Manas'}
console.log(Object.values(obj))
for key, value pairs:
const arr = [];
for(let key in obj){
arr.push([key,obj[key]])
}
console.log(arr)

Merging or appending array of objects in different object

I am using angularjs where I have a $scope.var1 ={a:10, b:20, c:30}; in which I want to append another value(s) which is infact an array of objects i.e. $scope.myobjects=[{m:10, n:30}, {x:6, y:8}, ....]; after appending this value my $scope.var1 should look like, $scope.var1={a:10, b:20, c:30, m:10, n:30, x:6, y:8};
any idea please.
Thanks
obj ={a:10, b:20, c:30};
arr=[{m:10, n:30}, {x:6, y:8}];
arr.forEach(function(a){
Object.keys(a).forEach(function(key){
obj[key]=a[key];
})
})
console.log(obj);
You could iterate the array and use Object.assign.
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
If not on the user agent available, like on IE, you could use a polyfill.
var target = { a: 10, b: 20, c: 30 };
objects = [{ m: 10, n: 30 }, { x: 6, y: 8 }];
objects.forEach(function (o) {
Object.assign(target, o);
});
console.log(target);
Object.assign.apply(null, [$scope.var1].concat($scope.myobjects))
Please try this one:
var var1 = { a: 10, b: 20, c: 30 };
myobjects = [{ m: 10, n: 30 }, { x: 6, y: 8 }];
myobjects.forEach(function (o) {
for (var p in o) {var1[p] = o[p]};
});
console.log(var1);
Note that this code simply add/update properties based on source object

Categories