How to delete particular elements in a array of objects [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have an array with multiple objects.How can i delete an element in a
object.
For example i have attached a image in that i need to delete
organization element.
Please help me out to fix.

var a = {name: 'pardeep', 'sirname': 'jain'}
delete a['name']
console.log(a);
Just use delete keyword for the key like this -
delete objectName['keyName']

Use the delete operator
const deleteAttribute = (array, attribute) => array.map(x => {
// Delete the attribute here
delete x[attribute];
return x;
});
const arr = [{
attr: 'hello',
color: 'red',
organization: 'Good'
}, {
attr: 'world',
color: 'blue',
organization: 'bad'
}];
console.log(deleteAttribute(arr, 'organization'));

You can use map and delete like below
var arr = [{
name: 'hi',
test: 'x',
organization: 'X'
}, {
name: 'guys',
test: 'y',
organization: 'Y'
}];
console.log(arr.map(x => { delete x.organization; return x}));

Related

Create options list for react Select from single dimension array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
I have an array like [ 123, 456 ] and it needs to be mapped into a react Select with label and value pairs so the "options" will be:
0: {label: "123", value: 123}
1: {label: "456", value: 456}
I just can't seem to get the map syntax to work for the source array (i.e. 0: 123, 1: 456)
You can write like this:
array.map((item)=> <Option label={item} value={item}/>)
This return an array of holding options with your label and value
If you need the options array you can write this:
let Myarray= [ 123, 456 ];
Myarray.map((item)=> <Option label={item} value={item}/>)
or If you need an array with label and value:
let Myarray= [ 123, 456 ];
let FinalArray=[];
Myarray.map((item)=>[...FinalArray,{label:item,value:item}])
if you want to put " to value
let Myarray= [ 123, 456 ];
let FinalArray=[];
Myarray.map((item)=>[...FinalArray,{label:item.toString(),value:item}])

How to get second duplicate value rather than first value from JSON Array in React JS using lodash? [duplicate]

This question already has an answer here:
Lodash uniqBy update the latest value
(1 answer)
Closed 9 months ago.
I am working on one project where I need to remove duplicate values from JSON array object with some specification in react JS. I have tried to remove using _.uniqBy but in the output it took very first value from duplicate value which is I don't want.
Suppose You have an array JSON like:
[ { id: 1, name: 'bob' }, { id: 2, name: 'bill' }, { id: 1, name: 'alice' } ]
using _.uniqBy I got [ { id: 1, name: 'bob' }, { id: 2, name: 'bill' }] this output.
but I want [ { id: 2, name: 'bill' }, { id: 1, name: 'alice' } ] this output.
As you can see I want output whose name is alice not bob along with id:1.
Can anyone help me?
Thank you.
My first thought is to use a reduce, and shove the items in a map, then get the values:
Object.values(items.reduce((map, item) => ({ ...map, [item.id]: item }), {}))
This is probably not very efficient though if you're dealing with large arrays of have performance concerns.
It's a quick and dirty one-liner. If you want something more efficient I'd take a look at the lodash source code and tweak it to your needs or write something similar:
https://github.com/lodash/lodash/blob/2f79053d7bc7c9c9561a30dda202b3dcd2b72b90/.internal/baseUniq.js

delete and modify properties in array inside json object [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 12 months ago.
Improve this question
Given the following JSON:
const myJson = {
id: 8,
active: true,
invoice: "2022/1001",
invoiceDate: "2022-02-02",
clientId: 1,
storeId: 1,
total: 76.95,
itens: [
{
id: 11,
quantity: 2,
price: 12.10,
total: 24.20,
productId: 1,
invoiceId: 8
},
{
id: 12,
quantity: 5,
price: 10.55,
total: 52.75,
productId: 2,
invoiceId: 8
}
]
};
I need a simple way to remove two attributes from the each item inside the 'itens' array, the properties are 'id' and 'invoiceId'. I also need to recalculate the 'total', coz I do not trust totally the source of the information, I rather multiply 'quantity' by 'price' myself.
I've produced this rather naive code:
myJson.itens.forEach(item => {
item.total =
item.quantity *
item.price;
delete item.id;
delete item.invoiceId;
});
And it works rather fine, however, no way that it must be it. Looks too lame and laborious to me. I'm exhausted googling for better ways of doing it.
Can it be done better?
Rather than mutating the original data, you could map it to a new object
const myJson = {"id":8,"active":true,"invoice":"2022/1001","invoiceDate":"2022-02-02","clientId":1,"storeId":1,"total":76.95,"itens":[{"id":11,"quantity":2,"price":12.1,"total":24.2,"productId":1,"invoiceId":8},{"id":12,"quantity":5,"price":10.55,"total":52.75,"productId":2,"invoiceId":8}]}
const newObject = {
...myJson, // keep the rest but map "itens"
itens: myJson.itens.map(({ id, invoiceId, ...iten }) => ({
...iten, // everything except "id" and "invoiceId"
total: iten.quantity * iten.price // recalc total
}))
}
console.log("newObject:", newObject)
.as-console-wrapper { max-height: 100% !important; }

How to get highest 3 value from object array - ES6/JS [closed]

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 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I simply want to get 3 highest price value objects as new array. How would I do that easily ?
For example i got array like this ..
const data =
[ { name: 'x', color: 'red', price: 15 }
, { name: 'y', color: 'black', price: 5 }
, { name: 'z', color: 'yellow', price: 25 }
, { name: 't', color: 'blue', price: 10 }
, { name: 'n', color: 'blue', price: 60 }
]
You can sort the array by the price property (with Array.sort) and get the first three items (with Array.slice):
const arr=[{name:"x",color:"red",price:15},{name:"y",color:"black",price:5},{name:"z",color:"yellow",price:25},{name:"t",color:"blue",price:10},{name:"n",color:"blue",price:60}];
const result = arr.sort((a,b) => b.price - a.price).slice(0, 3)
console.log(result)

JS array : filter() with map() vs forEach() [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 12 months ago.
Improve this question
Which is more optimized way .filter() + .map() OR .forEach() ?
Here is a sample array of objects:
var personnel = [
{
id: 5,
name: "Luke Skywalker",
pilotingScore: 98,
shootingScore: 56,
isForceUser: true,
},
{
id: 82,
name: "Sabine Wren",
pilotingScore: 73,
shootingScore: 99,
isForceUser: false,
},
{
id: 22,
name: "Zeb Orellios",
pilotingScore: 20,
shootingScore: 59,
isForceUser: false,
},
{
id: 15,
name: "Ezra Bridger",
pilotingScore: 43,
shootingScore: 67,
isForceUser: true,
},
{
id: 11,
name: "Caleb Dume",
pilotingScore: 71,
shootingScore: 85,
isForceUser: true,
},
];
And let say we want to get the final array giving only name and id where isForceUser=true
[ { id: 5, name: 'Luke Skywalker' }, 
{ id: 15, name: 'Ezra Bridger' }, 
{ id: 11, name: 'Caleb Dume' } ] 
Now there are 2 ways ti solve it :
By using .filter()+.map(), as shown below:
var APersonnel = personnel
.filter((person) => person.isForceUser)
.map((person) => ({ id: person.id, name: person.name }));
By using .forEach() and pushing a new object:
var BPersonnel = [];
personnel.forEach((person) => {
if (person.isForceUser) {
BPersonnel.push({ id: person.id, name: person.name });
}
});
Which one of the solutions defined above is better and why?
These are not the things you should seek performance improvements in. You are talking about 'personnel' here. Which is a fairly limited array set, I imagine. If you are having performance issues, I suggest you use the chrome dev performance tab to see what's causing it.
To answer your question, filter + map is semantically easier for the eye, which again is a personal opinion. Strictly performance wise the forEach is faster, where most likely a basic of for loop is even faster. But again, these are a few milliseconds we are talking about. Which does not justify the cost of rewriting :)
Another way can be to use reduce, less code, and only one loop:
const APersonnel = personell.reduce((acc, person) => {
if (person.isForceUser) {
acc.push({ id: person.id, name: person.name });
}
return acc;
}, []);
The best way is using foreach. Because map and filter are going to create two arrays. foreach doesn't create arrays. So foreach is the best one. look at those statements bellow,
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
I could be wrong, but I'm guessing forEach would be better.
In the first scenario, you are looping across 5 items, and then again across 3 items.
In the second scenario you are just looping across 5 items. And the if in the foreach is effectively being done in the filter anyway.
There may be an exception if you're working with an extremely large set of data because you would have both arrays in memory, but for anything short of that, I would recommend forEach

Categories

Resources