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)
Related
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']));
I have a problem. I have an object with this structure like this example.
{
"Name": "Peter",
"Username": "dummy",
"Age": 18,
"moreData": {
"tags": [1,2,3],
"hasCar": true,
"preferences": {
"colors": ["green", "blue"]
}
}
}
I would like to convert it to an array like the following. I am desperate and can not get any further. I have issues as soon I get some nested objects. Does someone have an idea how I can achieve this? Kind Regards
[
{
"key": "Name",
"val": "Peter"
},
{
"key": "Username",
"val": "dummy"
},
{
"key": "Age",
"val": "18"
},
{
"key": "tags",
"val": [1,2,3]
},
{
"key": "hasCar",
"val": true
},
{
"key": "colors",
"val": ["green", "blue"]
}
]
For this you need to first iterate through all the key value pairs of your object and change the specific type of data into name value pairs except the nested objects. If the value in the object at a certain key is an object then the same procedure has to be done for it. And since there can be N number of levels for this nested data thus we need a recursive function for it. Whenever we have to do a same set of processing for nested data then it always means it can be done using recursion. It can be done via for loops too but a recursive function is much clear and lesser to write.
function getData(data) {
let results = [];
Object.keys(data).forEach(key => {
// If the type of the data item is object and is not an array, go into recursion
if(typeof data[key] == 'object' && !Array.isArray(data[key])) {
results = results.concat(getData(data[key]));
} else {
results.push({ key, val: data[key] });
}
});
return results;
}
const data = {
"Name": "Peter",
"Username": "dummy",
"Age": 18,
"moreData": {
"tags": [1,2,3],
"hasCar": true,
"preferences": {
"colors": ["green", "blue"]
}
}
};
const results = getData(data);
console.log(results);
// [{"key":"Name","val":"Peter"},{"key":"Username","val":"dummy"},{"key":"Age","val":18},{"key":"tags","val":[1,2,3]},{"key":"hasCar","val":true},{"key":"colors","val":["green","blue"]}]
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);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
The problem
I have a Javascript array that can contains duplicates (only 2) having same value for the key color.
var array = [
{
"id": "1",
"color": "red",
"animal": null
},
{
"id": "2",
"color": "red",
"animal": "cat"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
I'd like to remove duplicates on key color and only keep the unique object having the key animal not null.
var uniqueArray = [
{
"id": "2",
"color": "red",
"animal": "cat"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
What I tried
var obj = {};
for (var i = 0; i < array.length; i++) {
obj[array[i]['name']] = array[i];
}
var uniqueArray = new Array();
for (var key in obj) {
uniqueArray.push(obj[key]);
}
Here's the result :
var uniqueArray = [
{
"id": "1",
"color": "red",
"animal": "null"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
I don't know how to choose which object I want to keep.
Note : I can't use ES6
I hope the value of animal should be null instead of 'nul' in the first.
var array = [
{
"id": "1",
"color": "red",
"animal": null
},
{
"id": "2",
"color": "red",
"animal": "cat"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
If you want to pick the unique values(objects in this case) based on color,it's better to create another object and put color as a key to get the unique values.
var obj = {};
array.forEach(a => {
if(!obj[a.color] && a.animal) {
obj[a.color] = a;
}
});
Now the object looks like following
Now you get an object containing unique object based on color and more importantly your animal property is not null.
You said you can't think of what to choose here.
IMO it's better to select the one having a value rather than a null value.
NOTE: the above code gives you an object but you can convert it to an array easily by following. Not entirely sure if Object.values is an es6 feature or not(didn't find anything on docs).
var arr = Object.values(obj);
If you don't like the above solution, you can iterate over the object and push it to an array.
var finalArr = [];
Object.keys(obj).forEach(function(key) {
finalArr.push(obj[key])
});
Just remove all the null values with a simple filter:
var array = [{"id":"1","color":"red","animal":"cat"},{"id":"2","color":"red","animal":"null"},{"id":"3","color":"green","animal":"dog"},{"animal":"dog"}];
var uniqueArray = array.filter(function(e) {
return e.animal != "null";
});
console.log(uniqueArray);
Without using ES6
var array = [{
"id": "1",
"color": "red",
"animal": "cat"
},
{
"id": "2",
"color": "red",
"animal": "null"
},
{
"id": "3",
"color": "green",
"animal": "dog"
}
];
var a = [];
var arr = [];
array.forEach(function(e, i) {
if (a.indexOf(e.color) == -1 && e.animal != "null") {
a.push(e.color)
arr.push(e)
}
})
console.log(arr)
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']);