I have severel Objects containing one sort of data:
Prices:
'btc-usd' : 2640, 'ltc-usd': 40, ...
Amount of Crypto:
'btc-usd': 2.533, 'ltc-usd': 10.42, ...
How can I take these Objects and create an Array of Objects like:
[ { name: 'Bitcoin', amount: 2.533, value: 2640, id: 'btc-usd' },
{ name: 'Litecoin', amount: 10.42, value: 40, id: 'ltc-usd' }, ...
]
Thanks a lot for your help!
You could map the keys of one of the objects to produce a new array of objects. You just have to make sure, that the key is in every of these objects.
const names = {
'btc-usd' : 'Bitcoin',
'ltc-usd': 'Litecoin',
...
}
const prices = {
'btc-usd' : 2640,
'ltc-usd': 40,
...
}
const amounts = {
'btc-usd': 2.533,
'ltc-usd': 10.42,
...
}
const cryptos = Object.keys(names).map((key, index) => ({
name: names[key],
amount: amounts[key] ,
value: prices[key]},
id: key
}));
You could use a hash map (e.g. 'btc-usd' => {name:"Bitcoin",...}) to create new objects. This hashmap can be easily converted to an array.
var input={
value:{'btc-usd' : 2640, 'ltc-usd': 40},
amount:{'btc-usd': 2.533, 'ltc-usd': 10.42},
name:{"btc-usd":"Bitcoin","ltc-usd":"Litecoin"}
};
var hash={};
for(key in input){
var values=input[key];
for(id in values){
if(!hash[id]) hash[id]={id:id};
hash[id][key]=values[id];
}
}
var output=Object.values(hash);
http://jsbin.com/fadapafaca/edit?console
Here's a generalized function, add, that accepts a field name and an object of values and maps them into a result object which can then be mapped into an array.
const amounts = {btc: 123.45, eth: 123.45};
const names = {btc: 'Bitcoin', eth: 'Etherium'};
const result = {};
const add = (field, values) => {
Object.keys(values).forEach(key => {
// lazy initialize each object in the resultset
if (!result[key]) {
result[key] = {id: key};
}
// insert the data into the field for the key
result[key][field] = values[key];
});
}
add('amount', amounts);
add('name', names);
// converts the object of results to an array and logs it
console.log(Object.keys(result).map(key => result[key]));
const prices = {
'btc-usd' : 2640,
'ltc-usd': 40
};
const amounts = {
'btc-usd': 2.533,
'ltc-usd': 10.42
};
First, create a dictionary of what each abbreviation stands for.
const dictionary = {
'btc': 'Bitcoin',
'ltc': 'Litecoin'
};
Then, populate an empty array with objects containing the relevant information. In each of these objects, the name would correspond to the relevant key within the dictionary object. At the same time, the amount and value would correspond to the relevant key within the amounts and prices objects respectively. Finally, the Id would correspond to the key itself.
const money = [];
for(let coin in prices) {
money.push({
name: dictionary[coin.substr(0, coin.indexOf('-'))],
amount: amounts[coin],
value: prices[coin],
id: coin
});
}
console.log(money);
Related
I have a Keys Array and Multiple Values Array . I want push values array into keys Array .
Example :-
data[0] :['ktCalender', 'presenter', 'emailId', 'topic', 'status'] // Keys
[1] : ['2022-05-05', 'abc', 'abc#gmail.com', 'cricket overview', 'sheduled'] // Values
[3]: ['2022-05-04', 'xyz', 'xyz#gmail.com', 'ApS', 'organized']. // Values
I want Answer like : [
{ktCalender:2022-05-05,presenter:'abc',emailId:'abc#gmail.com',topic:'cricket overview',status:'sheduled'},
ktCalender:'2022-05-04',presenter:'xyx',emailId:'xyz#gmail.com',topic:'APS',status:'organized'},
]
let data = ['ktCalender', 'presenter', 'emailId', 'topic', 'status'];
let Values = [];
Values[0] = ['2022-05-04', 'xyz', 'xyz#gmail.com', 'ApS', 'organized'];
Values[1] = ['2022-05-05', 'abc', 'abc#gmail.com', 'cricket overview', 'sheduled']
let result = [];
Values.forEach((val) => {
const obj = data.reduce((accumulator, element, index) => {
return {...accumulator, [element]: val[index]};
}, {});
result.push(obj);
});
console.log(result);
I havve two different arrays with different property names like below
arrayA = [
{ id: 20, name: 'Jason' },
{ id: 15, name: 'Harry' },
{ id: 5, name: 'Clara' },
{ id: 9, name: 'Melonie' }
]
arrayB = [
{ courseID: 12, studentID: 20 },
{ courseID: 12, studentID: 15 }
]
I want to compare these two different arrays and remove unmatched ids from arrayA. For comparison, id field of arrayA and studentID field of arrayB matters. if these fileds aren't equal to each other, they should be removed from arrayA.
Expected is below
arrayA = [{id: 20, name: 'Jason' }, { id: 15, name: 'Harry' }]
Here is what I tried below but didn't work. Gave me empty array.
filteredElements = this.arrayA.map(e => e.id).filter(
val => this.arrayB.indexOf(val.studentID) !== -1
);
You can do that in following steps:
Use map() on arrayB and create array of courseID.
Then create a Set() from that Array
Then use filter() arrayA and check whether id of object exists in above created Set or not using Set.prototype.has()
const arrayA = [{id:20,name:'Jason'},{id:15,name:'Harry'},{id:5,name:'Clara'},{id:9,name:'Melonie'}]
const arrayB =[{courseID:12,studentID:20},{courseID:12,studentID:15}];
const ids = new Set(arrayB.map(x => x.studentID));
const res = arrayA.filter(x => ids.has(x.id));
console.log(res);
let arrayA = [{id: 20,name: 'Jason'},{id: 15,name: 'Harry'},{id: 5,name: 'Clara'},{id: 9,name: 'Melonie'}]
let arrayB = [{courseID: 12,studentID: 20},{courseID: 12,studentID: 15}];
let filtered=arrayA.filter(obj =>{ if(arrayB.find(course => course.studentID == obj.id))return true;return false;
});
console.log(filtered);
Try this:
var studentIds = arrayB.map(course => course.studentID);
var result = arrayA.filter(student => studentIds.includes(student.id));
The variable result contains your result.
Create a dictionary from courseMembers, keyed on studentID, to enable O(1) lookup.
Filter students according to the dictionary.
const students = [{id:20,name:'Jason'},{id:15,name:'Harry'},{id:5,name:'Clara'},{id:9,name:'Melonie'}]
const courseMembers = [{courseID:12,studentID:20},{courseID:12,studentID:15}]
function withCourses(students, courseMembers) {
const map = courseMembers.reduce((acc, {studentID}) =>
(acc[studentID] = true, acc), {})
return students.filter(({id}) => map[id])
}
const result = withCourses(students, courseMembers)
console.log(result) // [{ id:20, name:"Jason" },{ id:15, name:"Harry" }]
Ive been trying combinations but can't figure this out. I am trying to pull out an array containing just the values from a value pair within an array containing objects.
INPUT
const myUsers = [
{ id: '1', name: 'bob' },
{ id: '56', name: 'bert' },
{ id: '32', name: 'Jenny' }
]
REQUIRED OUTPUT
[1,56,32]
CURRENT CODE
const idRecordsOnly = myUsers.map(item => {
const container = {};
container[item.id] = container[item.id]
return container;
})
console.log(idRecordsOnly)
Thanks Aurabliss! the answer is below
const idRecordsOnly = myUsers.map(item =>item.id)
I want to filter items from the categories array based on the criteria in the otherCategories array.
If otherCategories contains an object where title matches one title from categories.subCategory[i].title and name matches categories.subCategory[i].details.name, then filter only that object e.g "item1" from categories.
var categories = [
{
title:"item1",
subCategory:[
{
title:"subCat1",
details:{
name:"detail1",
email:"test#test.com"
}
},
{
title:"subCat2",
details:{
name:"detail2",
email:"test#test.com"
}
}
]
},
{
title:"item2",
subCategory:[
{
title:"subCat1",
details:{
name:"detail3",
email:"test#test.com"
}
},
{
title:"subCat2",
details:{
name:"detail2",
email:"test#test.com"
}
}
]
}
]
var otherCategories = [
{
title:"subCat1",
name:"detail1"
}
]
Expected result
categories = [
{
title:"item1",
subCategory:[
{
title:"subCat1",
details:{
name:"detail1",
email:"test#test.com"
}
},
{
title:"subCat2",
details:{
name:"detail2",
email:"test#test.com"
}
}
]
}]
Use Array.reduce, Array.filter & Array.some
Convert the otherCategories array to an object with title as key and name as value
Filter categories array where some subCategory exists with matching values
var categories = [{title:"item1",subCategory:[{title:"subCat1",details:{name:"detail1",email:"test#test.com"}},{title:"subCat2",details:{name:"detail2",email:"test#test.com"}}]},{title:"item2",subCategory:[{title:"subCat1",details:{name:"detail3",email:"test#test.com"}},{title:"subCat2",details:{name:"detail2",email:"test#test.com"}}]}];
var otherCategories = [{title:"subCat1",name:"detail1"}];
var obj = otherCategories.reduce((a,c) => Object.assign(a,{[c.title]:c.name}), {});
categories = categories.filter(v => v.subCategory.some(o => obj[o.title] === o.details.name));
console.log(categories);
You could map the categories to the results by filtering the subCategories:
function matches(sub, filters) {
return filters.some(filter => filter.title === sub.title && filter.name === sub.name);
}
const result = categories.map(({ title, subCategories }) => ({ title, subCategories: subCategories.filter(sub => matches(sub, otherCategories)) }));
Another approach that will usually work for simple objects like the ones in your example, is to convert your otherCategories array to an array of "stringified" objects, and then filter categories by comparing "stringified" versions of the desired subCategory key value pairs to the converted otherCategories array.
Important to note, however, that object property order is not guaranteed in JavaScript (although many browsers will preserve property order). That means that this approach may not work in some situations and an approach like the one suggested by #NikhilAggarwal is more stable.
For example:
const categories = [{title: "item1", subCategory: [{title: "subCat1", details: {name: "detail1", email: "test#test.com"}},{title: "subCat2", details: {name: "detail2", email: "test#test.com"}}]}, {title: "item2", subCategory: [{title: "subCat1", details: {name: "detail3", email: "test#test.com"}},{title: "subCat2", details: {name: "detail2", email: "test#test.com"}}]}];
const otherCategories = [{title: "subCat1", name: "detail1"}];
const matches = otherCategories.map((item) => JSON.stringify(item));
const results = categories.filter((item) => {
for (const sub of item.subCategory) {
const match = JSON.stringify({title: sub.title, name: sub.details.name});
if (matches.includes(match)) {
return true;
}
return false;
}
});
console.log(results);
If I have an array of objects like this:
var mountains = [
{ name: 'Kebnekaise', elevation: 2106 },
{ name: 'Mount Ngauruhoe', elevation: 2291, comment: 'aka Mount Doom' }
];
How to get all unique keys i.e. ['name', 'elevation', 'comment']?
In ECMAScript 2015, it's really simple:
let mountains = [
{ name: 'Kebnekaise', elevation: 2106 },
{ name: 'Mount Ngauruhoe', elevation: 2291, comment: 'aka Mount Doom' }
];
let uniqueKeys = Object.keys(Object.assign({}, ...mountains));
Using ES6, one could do
var unique = new Set([].concat.apply([],mountains.map(Object.keys)))
Without ES6, something like
var unique = [].concat.apply([],mountains.map(Object.keys)).filter(function(value,i,arr) {
return arr.indexOf(value) === i;
});
You could iterate over the array of objects and iterate over each element's keys with Object.keys(obj), adding them to a hash to avoid duplicates:
function getKeySet (data) {
var keys = {};
data.forEach(function (datum) {
Object.keys(datum).forEach(function (key) {
keys[key] = true;
});
});
return Object.keys(keys);
}
Alternately you could add all the keys to an array and filter out duplicates. Either way this will be O(nm) where n is the number of elements in the array and m is the average number of keys.