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);
Related
I have two arrays and I would like to compare if these arrays have duplicated values, then return the values that aren't duplicates. Based on these two arrays I would like to return the string Eucalipto.
const plants = [
{
id: 59,
kind: "Cana-de-açucar"
},
{
id: 60,
kind: "Citros"
}
];
const auxPlants = [
"Cana-de-açucar",
"Citros",
"Eucalipto"
]
You can use Array#map to find all the kind values, pass that to the Set constructor, and then use Array#filter to find all elements of the array not in that Set.
const plants = [
{
id: 59,
kind: "Cana-de-açucar"
},
{
id: 60,
kind: "Citros"
}
];
const auxPlants = [
"Cana-de-açucar",
"Citros",
"Eucalipto"
];
const set = new Set(plants.map(({kind})=>kind));
const res = auxPlants.filter(x => !set.has(x));
console.log(res);
sounds like you want to filter the array of values you're interested in based on if they're not found in the other array, like so:
const nonDuplicates = auxPlants.filter(a => !plants.find(p => p.kind === a))
it's unclear if you'd also want values from the plants array that are non duplicate as well, or if you're only interested in uniques from the auxPlants array
This is the solution to it, I have explained it's working using comments
// create a set in order to store values in it
// assuming you have unique values
let set = new Set();
// iterating over array of object and storing the value of 'kind' in the set
for(obj of plants){
set.add(obj.kind);
}
// iterating over array and checking for values in set,
// if not in set then printing it
for(ele of auxPlants){
if(!set.has(ele)){
console.log(ele);
}
}
As said, please search for an already posted solution first. Here's what I found.
Anyhow, the solution would be to separate the types of plants from the first array, as so:
const plantsTypes = plants.map(obj => obj.kind)
Then, filter out the non duplicates:
const nonDuplicates = auxPlants.filter(plant => !plantsTypes.includes(plant))
Note that it matters which array you call the .filter() function on.
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%;})
SO I have array1 with values ["folderid":"DTSZ", "folderid":"IEACF6FVGG", "folderid":"IEACKQC6A"] and another array 2 with values ["title":"firsttitle", "title":"second","title":"thirdtitle"]
Now lets say using javascript i want to save it as json object.
[
{"folderid":"DTSZ","title":"firsttitle"},
{"folderid":"IEACF6FVGG", "title":"second"},
{"folderid":"IEACKQC6A", "title":"thirdtitle"}
]
I trying looping and concat but didn't work properly.
array1= ["folderid":"DTSZ", "folderid":"IEACF6FVGG", "folderid":"IEACKQC6A"] ;
array2 = ["title":"firsttitle", "title":"second","title":"thirdtitle"];
Get array with json objects
[
{"folderid":"DTSZ","title":"firsttitle"},
{"folderid":"IEACF6FVGG", "title":"second"},
{"folderid":"IEACKQC6A", "title":"thirdtitle"}
]
In JavaScript an array has just values, in you examples the array is invalid since you try to add direct key: values elements . i.e.
["folderid":"DTSZ"] // invalid !! (notice semicolon)
["folderid", "DTSZ"] // VALID (notice comma)
If you want to translate to a valid array and then to an object, you could use something like entries, which are array of arrays.
Let's take your first example and convert it to entries:
const arr1 = [["folderid", "DTSZ"], ["folderid", "IEACF6FVGG"], ["folderid","IEACKQC6A"]]
Then to convert this to object you can use Object.fromEntries just like this:
const obj1 = Object.fromEntries(entries);
So, focus first to convert your initial invalid arrays to entries, and then the job is done!
use the following code.
var a = [{ "folderid": "DTSZ" }, { "folderid": "IEACF6FVGG" }, { "folderid": "IEACKQC6A" }]
var b = [{ "title": "firsttitle" }, { "title": "second" }, { "title": "thirdtitle" }]
var newObject = a.map((o, index) => {
const temp = Object.assign(o, b[index]);
return temp;
});
console.log('output ---- ', newObject)
What I am trying to accomplish is from an array, I want to map all of those values into one object. For example, if I have the following data below
const myKeys = ["prop_1", "prop_2", "prop_3"];
When I map over this array I would like to return an object with 3 properties from the array listed above. Something like this.
const myKeysObj = myKeys.map( key => {
// expected outcome {"prop_1" : "some_value", "prop_2": "some_value", "prop_3": "some_value"}
// actual outcome {key: "some_value"}
return {[key]: "some_value"}
})
What can I do to have all three of my props in my array to be properties for a each object returned?
It looks like you want to reduce the keys into an object, in which case reduce is more appropriate than .map:
const myKeys = ["prop_1", "prop_2", "prop_3"];
const output = myKeys.reduce((a, key) => {
a[key] = 'some_value';
return a;
}, {});
console.log(output);
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})