I have an array of objects:
boxes= [{"itemsId":19,"quantity":0},{"itemsId":1053,"quantity":1},{"itemsId":1056,"quantity":1}];
How to pair values of objects from array?
Here's what I'd like boxes to look like:
boxes= [{"itemsId":quantity},{"itemsId":quantity},{"itemsId":quantity}];
ie.
boxes= [{"19":0},{"1053":1},{"1056":1}];
You can try with Array.prototype.map():
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
In each iteration set the value of itemsId as the key and the value of quantity as the value for that key.
var boxes= [{"itemsId":19,"quantity":0},{"itemsId":1053,"quantity":1},{"itemsId":1056,"quantity":1}];
boxes = boxes.map(i => ({[i.itemsId]:i.quantity}));
console.log(boxes);
You can use map to return an array and inside the callback return an object.Use square notation to create the object key. Since object key is unique the new value will overwrite old value inside an object
let boxes = [{
"itemsId": 19,
"quantity": 0
}, {
"itemsId": 1053,
"quantity": 1
}, {
"itemsId": 1056,
"quantity": 1
}];
let newData = boxes.map(function(elem) {
return {
[elem.itemsId]: elem.quantity
}
});
console.log(newData)
Using map()
var boxes = [{"itemsId":19,"quantity":0},{"itemsId":1053,"quantity":1},{"itemsId":1056,"quantity":1}];
var result = boxes.map(({itemsId, quantity}) => ({[itemsId]: quantity}))
console.log(result)
Related
I have two arrays array1 and array 2.Array1 have values with a key name "discount_price" and array2 have values with key name "regular_price".
eg:
discount_price_array,
regular_price_array
When i merge them using array merge i get a single array with combined values. i.e if array1 has 10 elements and array2 has 10 elements it merges into an array with 20 elements. merged_array.
what i want is instead an array with eg:
array{"discount_price":10,"regular_price":2},
array{"discount_price":4,"regular_price":3},
How can i achieve this ?
$(values).each(function(key, value) {
//console.log(value);
if( value.discount_price !==undefined){
discount_price_array.push({ discount_price: value.discount_price })
}
});
$(values).each(function(key, value) {
//console.log(value);
if( value.regular_price !==undefined){
regular_price_array.push({ regular_price: value.regular_price })
}
});
var finalarray =$.merge(discount_price_array,regular_price_array
)
Using map and 'destructuring (...)'
map: lets to iterate over an array and return the same length new array, where you decide what will be returned in every iteration.
(...) spread , allows you to spread the (outer properties) properties in a new object or array, you are basically assigning all object properties to new object, since you are spreading two object in the same new object, they are being merged.
// if both of them have the same length
let arr1 = [{'property1': 10 }, {'property1': 10 },];
let arr2 = [{'property2': 20 }, {'property2': 20 },];
let result = arr1.map((object, index)=> ({...object, ...arr2[index] }));
console.log(result);
simple map only
// if you want to pick which property to assign
let arr1 = [{'property1': 10 }, {'property1': 10 }];
let arr2 = [{'property2': 20 }, {'property2': 20 }];
let result = arr1.map((object, index)=> {
object['property2'] = arr2[index]['property2'];
return object;
});
console.log(result);
Say I have an object structured like this:
const carObj = {"1234":"Corvette","4321":"Subaru","8891":"Volvo"};
And I have an array that represents the key (or ID):
const myArray = [1234, 4321, 8891, 1234, 4321]
I want a loop, function, or something that will go through the object of arrays and return the value for the corresponding key. I am using vue.js and attempting to do this in a computed method. Any help would be much appreciated.
Expected output:
Corvette
Subaru
Volvo
Corvette
Subaru
Just map the numbers array the returns new one based on the keys of the object :
const result = myArray.map(item=>carObj[item])
computed property :
computed:{
result(){
return this.myArray.map(item=>this.carObj[item])
}
}
const carObj = {"1234":"Corvette","4321":"Subaru","8891":"Volvo"};
const myArray = [1234, 4321, 8891, 1234, 4321];
myArray.forEach((item) => {
console.log(carObj[item]);
});
I am trying to filter an object with another object inside of an array.
To be more precise, I am trying to compare the keys of the object inside the array, to the keys of my main object. If the values are the same, I want to return the value corresponding to those keys.
Here's an example:
var a = {
"maths":"A++",
"literature":"C-",
"sports":"B+",
"biology":"D",
"chemistry":"A",
"english":"A+",
"physics":"C+"
}
var b = [{
"maths":"Mathematics",
"biology":"Biology",
"physics":"Physics"
}]
I wanna check if any of the keys in object b are inside object a and if they are, I want to return their value into array. For example, I want to return ["A++","D","C+"]
I've tried using filter and Array.prototype.some but I couldn't figure out anything. Any advice on how should I achieve this?
First make an array or Set of all the keys inside b, then use .map to access each key on the a object:
var a = {
"maths":"A++",
"literature":"C-",
"sports":"B+",
"biology":"D",
"chemistry":"A",
"english":"A+",
"physics":"C+"
}
var b = [{
"maths":"Mathematics",
"biology":"Biology",
"physics":"Physics"
}];
const keys = b.flatMap(Object.keys);
const arr = keys.map(key => a[key]);
console.log(arr);
I'm assuming that you want to handle multiple objects in b.
If so and if you want one array for each object in b then you could do something like:
var a = {
"maths":"A++",
"literature":"C-",
"sports":"B+",
"biology":"D",
"chemistry":"A",
"english":"A+",
"physics":"C+"
}
var b = [{
"maths":"Mathematics",
"biology":"Biology",
"physics":"Physics"
},{
"maths":"Mathematics",
"biology":"Biology",
"english":"English"
}]
const result = b.map(obj => Object.keys(obj).map(key => a[key]));
console.log(result);
If you are dealing with a single object in the array b, then you can do this:
var a = {
"maths":"A++",
"literature":"C-",
"sports":"B+",
"biology":"D",
"chemistry":"A",
"english":"A+",
"physics":"C+"
}
var b = [{
"maths":"Mathematics",
"biology":"Biology",
"physics":"Physics"
}]
const valuesInAndB = Object.keys(a).reduce((acc,x) => {
if (b[0][x]) {
return acc.concat(a[x]);
}
return acc;
}, []);
console.log(valuesInAndB);
However, if the objects in b will be greater than one then as answered by #certainperformance you could get all the keys in b and map through a with those keys.
const keysInB = b.flatMap(Object.keys);
keysInB.map(key => a[key]);
flatMap is not available in some older browsers, please keep that in mind.
I have tried to take the particular array value of key from a JSON object and store that in an array which will be look like this.
Example:
var obj = { "1":{"class":2,"percent":0.99,"box":[0.2,0.3,0.4,0.5]},
"2":{"class":2,"percent":0.99,"box":[0.12,0.23,0.45,0.56]},
"3":{"class":2,"percent":0.99,"box":[0.52,0.83,0.34,0.59]}
}
and so on like this
Now i need to take the value of key "box" and store in an array.
var list = []
list = [[0.2,0.3,0.4,0.5],[0.12,0.23,0.45,0.56],[0.52,0.83,0.34,0.59]]
But, i tried multiple ways to store the array inside the array, but i could able to get like this when i printed the list
list = 0.2,0.3,0.4,0.5,0.12,0.23,0.45,0.56,0.52,0.83,0.34,0.59
You can use Object.keys (which returns an array of all key of your json) in combination with array’s map to transform your json into a new array:
const boxes = Object.keys(obj).map(key => obj[key].box)
You can also use Object.values, which is actually nicer in your case:
const boxes = Object.values(obj).map(value => value.box)
How it works
Object.keys return an array:
Object.keys(obj) // ["1", "2", "3"]
then you can map over them to get the value of each item:
Object.keys(obj).map(key => obj[key]) // [{box: [...]}, {box: [...]}, {box: [...]}]
then in array.map's callback, you can simply only return the box value:
Object.keys(obj).map(key => obj[key].box) // [[...], [...], [...]]
Without Object.keys()
function getBoxes (object) {
var boxes = [];
for (var key in object) {
if (!object.hasOwnProperty(key)) continue;
boxes.push(object[key].box);
}
return boxes;
}
console.log(getBoxes(obj))
for...in can loop through object's properties, but it'll also loop over inherited properties, therefore we need to guard the loop with object.hasOwnProperty(key).
Object.keys(): Return an array of all enumerable property names of an object
Object.values(): Return an array of all enumerable values of an object
array.map(): Return a new array with each item of the original array transformed in a given callback function
array.slice(): Return a shallow copy of the original array
Try this:
Object.values(obj).map(x=>x.box);
var obj = { "1":{"class":2,"percent":0.99,"box":[0.2,0.3,0.4,0.5]},
"2":{"class":2,"percent":0.99,"box":[0.12,0.23,0.45,0.56]},
"3":{"class":2,"percent":0.99,"box":[0.52,0.83,0.34,0.59]}
}
let list = Object.values(obj).map(x=>x.box);
console.log(JSON.stringify(list))
The Object.values returns array of obj values, then we use map to iterate over that values (we use arrow function) and create new array with box values.
Check next example:
1) First, use Object.keys() to get an array with the keys of the object.
2) Second, loop on every key and access the box property of the object associated with every key, then push this box property on a new array.
var obj = {
"1": {"class":2, "percent":0.99, "box":[0.2,0.3,0.4,0.5]},
"2": {"class":2, "percent":0.99, "box":[0.12,0.23,0.45,0.56]},
"3": {"class":2, "percent":0.99, "box":[0.52,0.83,0.34,0.59]}
};
var arrayOfArrays = [];
Object.keys(obj).forEach(function(k){
arrayOfArrays.push(obj[k].box);
});
console.log(arrayOfArrays);
Here is (just for fun) another alternative using the reduce() method:
var obj = {
"1": {"class":2, "percent":0.99, "box":[0.2,0.3,0.4,0.5]},
"2": {"class":2, "percent":0.99, "box":[0.12,0.23,0.45,0.56]},
"3": {"class":2, "percent":0.99, "box":[0.52,0.83,0.34,0.59]}
};
const reducer = (accumulator, currVal) => {
accumulator.push(currVal.box);
return accumulator;
};
arrayOfArrays = Object.values(obj).reduce(reducer, []);
console.log(arrayOfArrays);
I have an array of objects like so:
array = [{item_name: "necklace", quantity: "2"},
{item_name: "necklace", quantity: "4"},
{item_name: "bracelet", quantity: "5"}];
I would like to merge these objects in the array to end up with an array that looks like this:
array = [{item_name: "necklace", quantity: "6"},
{item_name: "bracelet", quantity: "5"}];
I'm unsure how to begin to tackle this. I have tried concat and merge but these override the values. Do I need to map?
Any help would be greatly appreciated!
You can just simply loop over the array and push the values into a new array, checking first to see if the item_name is already in there.
An easier way to check if the object is already in the new array is to create an object with the item_name and its position in the new array. Otherwise, you'd need to loop over the new array each time to check.
Try this:
function merge_data(array){
var new_array = [],
item_map = {};
// Loop over the array
array.forEach(function(v){
var item = v.item_name;
// The object is not already in the new array
if(item_map[item] === undefined){
// Push the object and save its index
item_map[item] = new_array.length;
// WARNING: This pushes a *reference* to `v` into the new array
// which means when I update `new_array[pos]`, it'll also update
// this object in the *original* array
//new_array.push(v);
new_array.push({
item_name: item,
quantity: v.quantity
});
}
// The object is already in the new array
else{
// Get its index and update the quantity
var pos = item_map[item],
// quantity is a string, we need to make it into an int
quantity = parseInt(new_array[pos].quantity, 10);
new_array[pos].quantity = quantity + parseInt(v.quantity, 10);
}
});
return new_array;
}
// Now `array` will have the merged data
array = merge_data(array);
console.log(array);