Modify all object inside an array of objects - javascript

I have an Array of objects like this :
let cars = [
{
"color": "purple",
"type": "minivan",
"registration": new Date('2017-01-03'),
"capacity": 7
},
{
"color": "red",
"type": "station wagon",
"registration": new Date('2018-03-03'),
"capacity": 5
},
{
...
},
...
]
I want to make a change on all objects and return this array without unnecessary information ( I don't need to get the type and registration ) and have my array of objects like this:
let cars = [
{
"color": "purple",
"capacity": 7
},
{
"color": "red",
"capacity": 5
},
{
...
},
...
]

Here is an answer. You can use it for typescript too.
let cars = [
{
"color": "purple",
"type": "minivan",
"registration": new Date('2017-01-03'),
"capacity": 7
},
{
"color": "red",
"type": "station wagon",
"registration": new Date('2018-03-03'),
"capacity": 5
},
]
let newCars = cars.map(function (car) {
return {"color" : car.color, "type": car.type};
});
console.log(newCars);

Use forEach:
cars.forEach(car => {
delete car.registration
delete car.type
})
Alternatively, if you want to create a new array, you can use the map function:
const newCars = cars.map(car => {
return { color: car.color, capacity: car.capacity }
})

You can iterate over each item in the array, and remove what you don't need. But that's just Javascript. For Typescript, if you want to update the type of the array as well, you may use casting:
const newCars = cars.map(car => {
delete car.registration;
delete car.type;
return car;
}) as {color: string; capacity: number}[];

You can use lodash
_.map(cars, _.partialRight(_.pick, ['color','capacity']));

Related

Array item using its own parent object index as its value?

lets say we have :
let array_of_objects = [
{
"color": "purple",
"type": "minivan",
"id": this.object.index // i know this is not valid code,but can this somehow get its own index within the array as value ?
},
{
"color": "red",
"type": "station wagon",
"id": this.object.index //this should be 1
}
]
Actual question in code comments..
what i'm trying to do is to fill a form's inputs using an object,and i want to be able to display the actual index of the object within the array in one of the inputs
instead of using index as id I suggest create a complex id or you can use uuid() library for creating unique user id uuid npm
import { v4 as uuidv4 } from 'uuid';
array_of_objects = array_of_objects.map((item, index) => ({ id: uuidv4(), ...item}))
console.log(array_of_objects);
let array_of_objects = [
{
"color": "purple",
"type": "minivan"
},
{
"color": "red",
"type": "station wagon"
}
];
array_of_objects = array_of_objects.map((item, index) => ({ id: index, ...item}))
console.log(array_of_objects);
Just initialize the array without the id and add it afterwards using a for loop.
let array_of_objects = [
{
"color": "purple",
"type": "minivan",
},
{
"color": "red",
"type": "station wagon",
}
]
for (let i = 0; i < array_of_objects.length; i++) {
array_of_objects[i].id = i;
}
You can use Object.keys(arrayVarible) to get the indexes of array which outputs as an array as well.
let array_of_objects = [
{
"color": "purple",
"type": "minivan",
},
{
"color": "red",
"type": "station wagon",
}
];
console.log(Object.keys(array_of_objects))
Each time the the array changes or you fill the form run this code
console.log(array_of_objects.length-1)

Javascript -sort array based on another javascript object properties

I have one javascript array and one object . Need help to sort javascript object keys based on the order number in another array
In subgroup array , I have name , order number. Need to sort Offerings keys based on that order number
const subgroup = [
{
"code": "6748",
"name": "test123",
"orderNumber": "0"
},
{
"code": "1234",
"name": "customdata",
"orderNumber": "1"
}
]
const offerings = {
"customdata" : [
{
"code": "Audi",
"color": "black"
}
],
"test123" : [
{
"brand": "Audi",
"color": "black"
}
]
}
I believe this should work for you. I've added some comments in the code that should hopefully do an okay job of explaining what is happening.
var subgroup = [{
"code": "6748",
"name": "test123",
"orderNumber": "0"
}, {
"code": "1234",
"name": "customdata",
"orderNumber": "1"
}];
var offerings = {
"customdata": [{
"code": "Audi",
"color": "black"
}],
"test123": [{
"brand": "Audi",
"color": "black"
}]
}
function sortObjectFromArray(refArray, sortObject, orderKey = 'order', linkKey = 'key') {
// Get copy of refArray
let reference = refArray.slice();
// Sort sortObject [ into an array at this point ]
let sorted = [];
for (let key in sortObject) {
// Searches the refArray for the linkKey, and returns the intended index
let index = reference.find((item) => item[linkKey] === key)[orderKey];
// Places the sortObject's value in the correct index of the 'sorted' Array
sorted[parseInt(index)] = [key, sortObject[key]];
};
// Return an object, created from previous 'sorted' Array
return sorted.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, {});
};
offerings = sortObjectFromArray(subgroup, offerings, 'orderNumber', 'name');
console.log(offerings);

Find a value in an array of populated objects mongdb - lodash

Maybe this question is duplicate or asked several times in different ways but still haven't solved my problem. I am creating nodejs api returning 10,000 populated objects from mongodb. I want to filter array based on the object.
{color: red}
How can i use lodash filter to return array with containing specified filter object.
[
{
"value": 200,
"newEle": {
"gradient": "true",
"mode": {
"color": "red"
}
}
},
{
"value": 100,
"newEle": {
"gradient": "false",
"mode": {
"color": "blue"
}
}
}
]
If you are specifically trying to filter by just the color you can use vanilla JS's .filter() to get all the objects with the color property of red into a new array:
const arr = [
{
"value": 200,
"newEle": {
"gradient": "true",
"mode": {
"color": "red"
}
}
},
{
"value": 100,
"newEle": {
"gradient": "false",
"mode": {
"color": "blue"
}
}
}
],
color = "red",
res = arr.filter(obj => obj.newEle.mode.color === color);
console.log(res);
If you wish to use lodash specifically you can use _.filter():
const arr = [
{
"value": 200,
"newEle": {
"gradient": "true",
"mode": {
"color": "red"
}
}
},
{
"value": 100,
"newEle": {
"gradient": "false",
"mode": {
"color": "blue"
}
}
}
],
color = "red",
res = _.filter(arr, obj => obj.newEle.mode.color === color);
console.log(res);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
When using lodash, it's as simple as this.
let filtered_array = _.filter(myArr, { color: 'red' });
However, since you have nested nested objects, you'd want to create a predicate that accesses the nested value. You do this with an array.
let filtered_array = _.filter(myArr, ['newEle.mode.color', 'red']);

map whole array if value equal

I would like to map an array where if one of the values equal to a variable then I change the isChecked key for all objects in this array. for e.g.
input array:
[
[
{
"name": "size",
"value": "XS",
"isChecked": false
},
{
"name": "colors",
"value": "black",
"isChecked": false
}
],
[
{
"name": "size",
"value": "XXXL",
"isChecked": false
},
{
"name": "colors",
"value": "brown",
"isChecked": false
}
],
[
{
"name": "size",
"value": "S",
"isChecked": false
},
{
"name": "colors",
"value": "green",
"isChecked": false
}
]
]
input value: black
output:
[
[
{
"name": "size",
"value": "XS",
"isChecked": true
},
{
"name": "colors",
"value": "black",
"isChecked": true
}
],
[
{
"name": "size",
"value": "XXXL",
"isChecked": false
},
{
"name": "colors",
"value": "brown",
"isChecked": false
}
],
[
{
"name": "size",
"value": "S",
"isChecked": false
},
{
"name": "colors",
"value": "green",
"isChecked": false
}
]
]
maybe should i use some callback,promise? How to map this array? I have to somehow return to the value I missed. In this case, if the value in the array is found then all elements in this array should be marked as isChecked = true.
i've got something like this now:
this.allVariants.map((variant, key) => {
return variant.map((opts, k) => {
if (opts.value == val && !opts.isChecked) {
let mapped = variant.map(op => op.isChecked = true);
} else {
let mapped = variant.map(op => op.isChecked = false);
}
return opts
})
})
You could use map method and inside some to check if element exists in sub-array or not.
const data = [[{"name":"size","value":"XS","isChecked":false},{"name":"colors","value":"black","isChecked":false}],[{"name":"size","value":"XXXL","isChecked":false},{"name":"colors","value":"brown","isChecked":false}],[{"name":"size","value":"S","isChecked":false},{"name":"colors","value":"green","isChecked":false}]]
const res = data.map(arr => {
const check = arr.some(({value}) => value == 'black');
return check ? arr.map(e => ({...e, isChecked: true})) : arr
})
console.log(res)
Perhaps you're looking for something like this? As you can see there's a simple map function which will return an array of the relevant values depending on what was input into the function. It will simply map over the provided arrray and update the relevant objects, provided that the find function doesn't return null.
It achieves this by seeing if the provided value can be found within a nested array via using the found function that I've implemented, provided this returns true, it will then use the mutate function. The idea was that you may want to further change different properties on the given object(s) in future, hence why it has a dedicated function.
My answer is similar to #NenadVracar only I broke it up a little more into multiple functions that consume a single line.
let data = [[{name:"size",value:"XS",isChecked:!1},{name:"colors",value:"black",isChecked:!1}],[{name:"size",value:"XXXL",isChecked:!1},{name:"colors",value:"brown",isChecked:!1}],[{name:"size",value:"S",isChecked:!1},{name:"colors",value:"green",isChecked:!1}]];
// A function that states if relevant object with value exists.
let found = v => a => a.some(({value}) => value == v);
// A function used to return data that has been changed, specifically isChecked = true.
let mutate = a => a.map(i => ({...i, isChecked: true}));
// A function to return the desired array, takes an array and a value.
let map = v => a => a.map(o => found(v)(o) ? mutate(o) : o);
console.log(map('black')(data));

How does new Map() works in javascript when the json has keys with same name

I have a JSON structure and code like below :
const villages =
{
"lossesOccured":
[
{
"type": "destroyed",
"affectedOn": "humans",
"quantity": 120,
"reliefFund": 100000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
},
{
"type": "physicalDamage",
"affectedOn": "humans",
"quantity": 250,
"reliefFund": 50000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
},
]
}
const lossesArray = villages.lossesOccured
let myMap = new Map()
lossesArray.forEach(loss => {
if(loss.affectedOn === "humans"){
myMap.set(loss.affectedOn,loss)
}
})
console.log(myMap)
Initialised a new Map and assigned key,values to it.
Key is "affectedOn".
Since there are same key names(affectedOn) in many elements, map eliminates all duplicates and prints only one. Is there a way to print all the key values even-though it has same name.
Thanks in advance.
Output:
A Map has key-value pairs, similar to an object, and will have a value for every distinct key. (If you want to use keys k1 and k2, and k1 === k2, and you call myMap.set(k1 and then later myMap.set(k2, then the initial value assigned by k1 will be overwritten.)
If you want to turn everything in your input array into a Map, one way to make sure the keys are unique would be to make the keys objects (which won't be === to each other):
myMap.set({ key: loss.affectedOn }, loss);
const villages = {
"lossesOccured": [{
"type": "destroyed",
"affectedOn": "humans",
"quantity": 120,
"reliefFund": 100000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
},
{
"type": "physicalDamage",
"affectedOn": "humans",
"quantity": 250,
"reliefFund": 50000,
"location": {
"district": "thanjavur",
"villageName": "madukkur",
"pincode": "614903"
}
},
]
}
const lossesArray = villages.lossesOccured
const myMap = new Map();
lossesArray.forEach(loss => {
if (loss.affectedOn === "humans") {
myMap.set({ key: loss.affectedOn }, loss);
}
});
console.log(myMap);

Categories

Resources