This question already has answers here:
Create an object from an array of keys and an array of values
(9 answers)
Closed 1 year ago.
I have two arrays with the same length.
array1 = ['title', 'details', 'price', 'discount'];
array2 = ['product name', 'product details', 200, 20];
Want to convert them into one object like following
newObject = {
title: 'product name',
details: 'product details',
price: 200,
discount: 20
}
How to do that?
You can create the pairs using Array#map and convert the result into the object using Object#fromEntries:
const
array1 = ['title', 'details', 'price', 'discount'],
array2 = ['product name', 'product details', 200, 20];
const newObject = Object.fromEntries(
array1.map((e,i) => ([e, array2[i]]))
);
console.log(newObject);
Related
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 2 months ago.
I have a array like this:
let arr = [
{
index: 1,
price: "24.99"
},
{
index: 2,
price: "24.95"
},
{
index: 3,
price: "20.95"
},
]
I want only the prices now in the array like this:
let arr = ["24.99", "24.95", "20.95"]
How I make this ?
Seems like a perfect opportunity for map
arr = arr.map((el) => el.price)
Gives
[ "24.99", "24.95", "20.95" ]
Use the Array.map function:
const objarr = [{
index: 1,
price: "24.99"
},
{
index: 2,
price: "24.95"
},
{
index: 3,
price: "20.95"
},
]
const arr = objarr.map((element) => element.price);
console.log(arr);
This question already has answers here:
How to get the difference between two arrays of objects in JavaScript
(22 answers)
Array.includes() to find object in array [duplicate]
(8 answers)
Closed 11 months ago.
I have an array of available items:
const items = [{id: 1, title: Item 1}, {id: 2, title: Item 2}, {id: 3, title: Item 3}]
and an array of items that my user has purchased:
const purchasedItems = [{id: 1, title: Item 1}, {id: 2, title: Item 2}]
I want to display an array of items that are still available to them to purchase that they haven't bought yet, i.e. just item 3 in this case. So I want an array returned with just Item 3 in it.
I have tried:
const availableItems = items.filter(
(item) => !purchasedItems.includes(item)
)
However this just returns a list of all the items again.
Think I must be missing something quite obvious, any help appreciated!
includes won't work here because it will only compare the items with a strict equality (as in item1 === item2). It will only works if your items are the same objects with the same reference.
A little example:
const obj1 = { test: 1 };
const obj2 = obj1;
const obj3 = { test: 1 };
console.log(obj1 === obj2); // true
console.log(obj1 === obj3); // false
So, in your case, you have to do a more complex work in your filter function:
const availableItems = items.filter(item1 => !purchasedItems.some(item2 => item1.id === item2.id));
Use findIndex() instead of includes
const items = [{ id: 1, title: 'Item 1' }, { id: 2, title: 'Item 2' }, { id: 3, title: 'Item 3' }]
const purchasedItems = [{ id: 1, title: 'Item 1' }, { id: 2, title: 'Item 2' }]
const availableItems = items.filter((item) => (purchasedItems.findIndex(purchasedItem => purchasedItem.id === item.id) == -1))
console.log(availableItems)
This question already has answers here:
Intersect and merge two array of objects
(2 answers)
Closed 2 years ago.
I have two arrays of equal length, each does contain object data.
This is the example code of the first array ...
const array1 = [{
key: '5',
value: '550',
}, {
key: '6',
value: '750',
}];
And here is the code for the second one ...
const array2 = [{
type: 'Job',
status: 'Finished',
key : '5',
}, {
type: 'Ticket',
status: 'Processing',
key : '6',
}];
In order to further process my data I need an intersection of both arrays with their corresponding object items being merged. The result should look like this ...
[{
key: '5',
value: '550',
type: 'Job',
status: 'Finished',
}, {
key: '6',
value: '750',
type: 'Ticket',
status: 'Processing',
}]
What I have come up with so far is ..
array1.forEach(function (element) {
array2.forEach(function (element) {
return {
type: 'Ticket',
status: 'Processing'
};
});
});
I don't know how to create the expected result. How would a solution to my problem look like?
You could store the objects in a hash table by key and merge the other array with the data from the hash table.
const
array1 = [{ key: '5', value: '550' }, { key: '6', value: '750' }],
array2 = [{ type: 'Job', status: 'Finished', key: '5' }, { type: 'Ticket', status: 'Processing', key: '6' }],
temp = Object.fromEntries(array2.map(o => [o.key, o])),
result = array1.map(o => ({ ...o, ...temp[o.key] }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
It sounds like you need to combine objects in two arrays by their key.
Array methods are a good choice, but you should also look into other methods.
const combinedItemsArray = array1.map(item1 => {
const matchingItem = array2.find(item2 => item2.key === item1.key)
return {...item1, ...matchingItem }
})
This uses the spread operator to combine the values of items with matching keys.
Some things to consider:
Array.find only matches the first item in array 2 that satisfies the result. So if the arrays have items with duplicate keys, you need to modify this.
This will break down on a performance level if you have lots of items in your arrays (10s of 1000's). In that case the hash table answer might be a better approach.
its a great idea to refer to the common array methods often on mdn.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
use the sidebar to find the one that you might need!
Make use of Array.prototype.map which can be passed an additional target object to ... here one would use the second array from which one wants to retrieve the corresponding merger item.
The merging is done via Object.assign where one does merge both array items to a newly created object in order to not mutate any of the merger items of either involved array ...
const array1 = [{
key: '5',
value: '550',
}, {
key: '6',
value: '750',
}];
const array2 = [{
type: 'Job',
status: 'Finished',
key : '5',
}, {
type: 'Ticket',
status: 'Processing',
key : '6',
}];
function mergeWithSameIndexItemFromBoundArray(item, idx) {
const boundArray = this;
return Object.assign({}, item, boundArray[idx]);
}
console.log(
'merge result of array2 and array1 ...',
array2.map(mergeWithSameIndexItemFromBoundArray, array1)
);
console.log(
'merge result of array1 and array2 ...',
array1.map(mergeWithSameIndexItemFromBoundArray, array2)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
In case of arrays of non matching item orders one can build on the above approach of providing an additional target object to map.
This time it will not be the second array but a transformation of it; an object which has mapped all of this second array's items to it by using the very property name by which all the items are identified. For the OP's example this property name is key.
Thus one needs to write an additional function which does this mapping task. The next following example chooses an approach based on Array.prototype.reduce.
In addition the mapper function has to be rewritten in order to make use of the before created bound map by simply using an array item's key property instead of the array index from before ...
const array1 = [{
key: '5',
value: '550',
}, {
key: '7',
value: '320',
}, {
key: '6',
value: '750',
}];
const array2 = [{
type: 'Ticket',
status: 'Processing',
key : '6',
}, {
type: 'Job',
status: 'Finished',
key : '5',
}, {
type: 'Task',
status: 'Pending',
key : '7',
}];
function createKeyBasedItemMap(map, item) {
map[item.key] = item;
return map;
}
function mergeWithKeyBasedItemFromBoundMap(item) {
return Object.assign({}, item, this[item.key]);
}
console.log(
'map-based merge of unordered array2 and array1 items ...',
array2.map(
mergeWithKeyBasedItemFromBoundMap,
array1.reduce(createKeyBasedItemMap, {})
)
);
console.log(
'map-based merge of unordered array1 and array2 items ...',
array1.map(
mergeWithKeyBasedItemFromBoundMap,
array2.reduce(createKeyBasedItemMap, {})
)
);
console.log('\n');
console.log(
'proof of concept ... the item-map based on array1 ...',
array1.reduce(createKeyBasedItemMap, {})
);
console.log(
'proof of concept ... the item-map based on array2 ...',
array2.reduce(createKeyBasedItemMap, {})
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 2 years ago.
how do I find and return a specific object key and return as array in lodash.
const category = [
{ id: 123, name: "haha"},
{ id: 124, name: "haha2"},
{ id: 125, name: "haha3"},
]
how do i get this?
result: [123,124,125]
make for each loop to iterate over category and each element of category has id push it into empty arr
let result = []
const category = [
{ id: 123, name: "haha"},
{ id: 124, name: "haha2"},
{ id: 125, name: "haha3"},
]
category.forEach(c=>{
result.push(c.id)
})
console.log(result)
You can use Array.map:
category.map(item => item.id)
This question already has answers here:
How to get distinct values from an array of objects in JavaScript?
(63 answers)
Closed 5 years ago.
From the following object
items = [{
title = 'title 1',
category = 'foo'
},
{
title = 'title 5',
category = 'bar'
},
{
title = 'title n',
category = 'bar'
},
]
which
I receive dynamically at runtime
can have any length
where each category field can have one of up to items.length values
I want to get the set of all different values for the field category.
In the example above, the result of
get_all_possible_categories(items)
would be
['foo','bar'].
How can I implement
get_all_possible_categories(items) ?
Just map the values back to an array, using a Set to get unique values
items = [{
title : 'title 1',
category : 'foo'
},
{
title : 'title 5',
category : 'bar'
},
{
title : 'title n',
category : 'bar'
}
];
function get_all_possible_categories(arr) {
return [...new Set(arr.map( x => x.category))];
}
var result = get_all_possible_categories(items);
console.log(result);
You could take a Set and map all values of the wanted property.
At the end take an array and spread syntax ... for building a new array. The spread sytax takes the values of an iterable and insert them as parameters.
var items = [{ title: 'title 1', category: 'foo' }, { title: 'title 5', category: 'bar' }, { title: 'title n', category: 'bar' }],
values = [...new Set(items.map(o => o.category))];
console.log(values);