JSON object restructure using ES6 [duplicate] - javascript

This question already has answers here:
Sum of same object name in javascript
(4 answers)
Want to sum of values with same property name in object using javascript or jquery [closed]
(2 answers)
What is a efficient way to condense a List of objects to based on an object value?
(2 answers)
Reduce an Array of object based on value of attribute
(5 answers)
Closed 4 years ago.
I have something like this:
tires: [{
name: "fancyProduct1",
quantity: 1
}, {
name: "fancyProduct1",
quantity: 1
}, {
name: "fancyProduct1",
quantity: 1
}, {
name: "fancyProduct2",
quantity: 1
}];
What I'm trying to accomplish is
tires: [{
name: "fancyProduct1",
quantity: 3
}, {
name: "fancyProduct2",
quantity: 1
}]
Any ideas on best way to approach this?

You can use reduce to group the array into one object. Use Object.values to convert the object into an array.
let tires = [{"name":"fancyProduct1","quantity":1},{"name":"fancyProduct1","quantity":1},{"name":"fancyProduct1","quantity":1},{"name":"fancyProduct2","quantity":1}];
let result = Object.values(tires.reduce((c, {name,quantity}) => {
c[name] = c[name] || {name,quantity: 0}
c[name].quantity += quantity;
return c;
}, {}));
console.log(result);

Using Reduce will accomplish this:
var products = { tires: [ {name: "fancyProduct1", quantity: 1}, {name: "fancyProduct1", quantity: 1}, {name: "fancyProduct1", quantity: 1}, {name: "fancyProduct2", quantity: 1}] };
var result = products.tires.reduce((acc,current) => {
if (!acc[current.name]) {
acc[current.name] = { name: current.name, quantity: 0};
}
acc[current.name].quantity++;
return acc;
}, {});
var resultArray = Object.values(result);
console.log(resultArray);

Well you can use a simple Array.forEach() call to loop over the array items, along with Array.find() to check for the existence of your iterated item in the result array and do your logic accordingly.
This is how should be your code:
var result = [];
tires.forEach(function(el) {
let found = result.find(o => o.name === el.name);
if (found) {
found["quantity"] += el["quantity"];
} else {
result.push(el);
}
});
Demo:
var tires = [{
name: "fancyProduct1",
quantity: 1
}, {
name: "fancyProduct1",
quantity: 1
}, {
name: "fancyProduct1",
quantity: 1
}, {
name: "fancyProduct2",
quantity: 1
}];
var result = [];
tires.forEach(function(el) {
let found = result.find(o => o.name === el.name);
if (found) {
found["quantity"] += el["quantity"];
} else {
result.push(el);
}
});
console.log(result);

You can do something like this...
var newTries = tires.map(n => (
// logic for new array where you can get attributes of item in tires to create a new array.
console.log(n); // this can show what properties are available in the current item write it to the console.
)};
Hope this helps.

Related

How to group array of object by key value pairs using javaScript?

I just started learning JavaScript, I have this type of array, how I can turn this array of objects into key-value pairs like below, Any source and reference is acceptable.
Sample Array:
[
{Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1},
{Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1}
]
Expected Result:
{
"6d7e75e6-c58b-11e7-95-ac162d77eceb":1,
"6d2e75e6-c58b-11e7-95-ac162d77eceb":1
}
Using Array.prototype.Reduce:
const arr = [{Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1},{Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1}];
const result = arr.reduce((acc, { Id, qty }) => ({ ...acc, [Id]: qty }), {});
console.log(result);
Another approach, a little more beginner friendly.
const arr = [
{Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1},
{Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1}
];
const newObject = {}; // empty object
// loop over each element of the array
arr.forEach(element => {
// the key is the element identifier (Id) and the value is the element quantity (qty)
newObject[element.Id] = element.qty;
});
You can use a loop and add the item.Id as the key and the item.qty as the value in an empty object.
let arr = [{Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1},{Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1}]
let obj = {}
arr.forEach(item => {
obj[item.Id] = item.qty
})
console.log(obj)
You can easily achieve this result using forEach in a single line of code.
const arr = [
{ Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1 },
{ Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1 },
];
const result = {};
arr.forEach(({ Id, qty }) => (result[Id] = qty));
console.log(result);
You can achieve the desired result with below code
//input array
const arrList = [
{Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1},
{Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1}
]
function findArray(arr) {
//define a new array to store Id's
let newArray = [];
//iterate through array items
arr.forEach(item => {
newArray.push(item.Id);
});
return newArray;
}
//call findArray function to get desired output
console.log(findArray(arrList));
Using Object.fromEntries()
const
array = [{ Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1 }, { Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1 }],
object = Object.fromEntries(array.map(({ Id, qty }) => [Id, qty]));
console.log(object);
or, for some fragile novelty...
const
array = [{ Id: "6d7e75e6-c58b-11e7-95-ac162d77eceb", qty: 1 }, { Id: "6d2e75e6-c58b-11e7-95-ac162d77eceb", qty: 1 }],
object = Object.fromEntries(array.map(Object.values));
console.log(object);

How can i search in to array for duplicated objects?

i have array like this structure and want push some Non-duplicate objects
[
{
applicationNumber: "2",
id: "8cca5572-7dba-49de-971b-c81f77f221de",
country: 23,
totalPrice: 36
},
{
applicationNumber: "3",
id: "8cca5572-33333-49de-971b-c81f77f221de",
country: 1,
totalPrice: 2
}
]
i want to search on this array before push any other object on it to check existing object and after that if is not any existing object, push new object or if existing update that object only. how can i do this thing?
Try to create a function called addToArray that takes the original array and the new object to add as parameters, inside it find the index of that object of it already exist override it else push it at the end :
let arr = [{
id: 1,
country: 45
},
{
id: 2,
country: 23
},
{
id: 3,
country: 75
},
{
id: 4,
country: 39
}
]
function addToArray(ar, val) {
let index = ar.findIndex(item => item.id === val.id);
(index >= 0) ? ar[index] = val:ar.push(val)
}
console.log('before :',arr)
addToArray(arr, {
id: 2,
country: 86
})
console.log('after : ',arr)
You could use the ES6 Array.findIndex() function. Like so:
let sampleArray = [
{
applicationNumber: "2",
id: "8cca5572-7dba-49de-971b-c81f77f221de",
country: 23,
totalPrice: 36
},
{
applicationNumber: "3",
id: "8cca5572-33333-49de-971b-c81f77f221de",
country: 1,
totalPrice: 2,
}
];
const updateArr = newData =>
{
const existingIndex = sampleArray.findIndex(obj => obj.id === newData.id);
if (existingIndex >= 0)
sampleArray[existingIndex] = { ...sampleArray[existingIndex], ...newData };
else
sampleArray.push(newData)
}
const newData = { id: "8cca5572-33333-49de-971b-c81f77f221de", country: 67637674634 }
updateArr(newData);
console.log(sampleArray)
i use an event to run function on every change and after that use loop like below
vents.$on('newArr', (newArray) => {
let i;
for (i = 0; i < this.exportData.length; i++) {
let obj = this.exportData[i];
if (obj.id === newArray.id) {
delete this.exportData[i];
}
}
this.exportData.push(newArray);
});
i think it's simple and clear also if anyone think this way not optimize or not good tell me about that.

Javascript - Get unique and sorted array

I have an array with duplicate items. I want to filter that array to return only unique items, but that items have to be sorted based on how many times they were in initial array.
const initialArr = [
{
id: 1
},
{
id: 1
},
{
id: 2
},
{
id: 1
},
{
id: 3
},
{
id: 3
},
];
const expectedSortedResult = [
{
id: 1
},
{
id: 3
},
{
id: 2
}
]
Try to always post your attempt, no matter how far away from the solution it is.
You should research the following (and I solved it with these too):
Reduce (create object, groupBy and create __count property): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Convert this back to an array with Object.values(), Followed by
Sort (sort by __count): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Then you will need to delete that count property if you don't want it in your output, you can do this with Map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
const initialArr = [
{id: 1},
{id: 1},
{id: 2},
{id: 1},
{id: 3},
{id: 3},
];
const output = Object.values(initialArr.reduce((aggObj, item) => {
if (aggObj[item.id]){
aggObj[item.id].__count += 1
}
else{
aggObj[item.id] = item;
aggObj[item.id].__count = 1
}
return aggObj;
}, {}))
.sort((a,b) => b.__count - a.__count)
.map(a => {delete a.__count; return a});
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Filter array of objects but return only specific properties - JS [duplicate]

This question already has answers here:
Extract certain properties from all objects in array
(5 answers)
Closed 4 months ago.
How to filter an array of objects with a condition and return only specific properties of filtered objects?
I know we can use filter followed by map to achieve this. But I am looking for more simple solution.
For ex:
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}]
Suppose if I want only ids of name "lala".
Output should be,
[{id: 1}, {id: 3}]
The next simplest would be reduce
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}];
console.log(
arr.reduce((values, value) =>
{
if (value.name === 'lala') values.push({ id: value.id });
return values;
}, [])
);
You can simply use Array.prototype.reduce to combine both mapping and filtering in the same operation. If you want to make it super concise, you can use object destructuring in the second argument of the reduce callback:
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}];
let filteredMappedArr = arr.reduce((acc, { name, id }) => {
if (name === 'lala')
acc.push({ id });
return acc;
}, []);
console.log(filteredMappedArr);
filter followed by map is probably the most readable solution, but if you're looking to do it all in one step, you're looking at the classic for loop or using reduce.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
You can do it by using filter and map;
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}]
let res = arr.filter(item => item.id % 2 === 1).map(item => ({id: item.id}))
console.log(res);
You could take Array#flatMap and return either a new obejct or an empty array which has no value for flattening.
let array = [{ name: "lala", id: 1 }, { name: "coco", id: 2 }, { name: "lala", id: 3 }],
result = array.flatMap(({ id, name }) => name === 'lala' ? [{ id }] : []);
console.log(result);
using .filter() and .map() functions:
let arr = [{name:"lala", id: 1}, {name: "coco", id:2}, {name: "lala", id:3}]
let newArr = arr.filter((elm) => (elm.name === 'lala')).map( (elm) => {return {id:elm.id}});
console.log(newArr);
let arr = [
{ name: "lala", id: 1 },
{ name: "coco", id: 2 },
{ name: "lala", id: 3 },
];
let a = [];
arr.filter(({ name, id }) => {
if (name === "lala") {
a.push({ id });
}
});
console.log(a);
with filter we check for the condition where name matches 'lala' if yes then we push id to new array...that's simple

Javascript remove array from object where id [duplicate]

This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed 4 years ago.
Sorry for my bad English. If I have an array:
const myobj = [
{
id: 1,
name: 'First...'
},
{
id: 2,
name: 'Second...
}];
How can I remove, for example, the object with id 2? To leave the array only with first object. Which functions should I use? Thanks in advance.
Found solution:
function removeByKey(array, params){
array.some(function(item, index) {
if(array[index][params.key] === params.value){
array.splice(index, 1);
return true;
}
return false;
});
return array;
}
Then
removeByKey(myobj, {
key: 'id',
value: 2
})
http://jsforallof.us/2015/07/08/remove-object-by-key-from-array/
Use Array.prototype.filter which produces new array based on the provided condition.
const myobj = [{ id: 1, name: 'First...' }, { id: 2, name: 'Second...' }];
console.log(myobj.filter(v => v.id !== 2));
Similarly you can use Array.prototype.reduce
const myobj = [{ id: 1, name: 'First...' }, { id: 2, name: 'Second...' }];
console.log(myobj.reduce((acc, v) => v.id !== 2 ? acc.concat(v) : acc, []));
Using filter and assuming myobj is not constant you can do the following:
myobj = [
{
id: 1,
name: 'First...'
},
{
id: 2,
name: 'Second...'
},
{
id: 3,
name: 'Third...'
}
];
myobj = myobj.filter(v => v.id !== 2);
console.log(myobj);
first, you have an array, not an object in myobj, one way of many you could do this is to remove the item by filtering:
const myFilteredArray = myobj.filter(i => i.id !== 2);
See the javascript filter function

Categories