Splicing JSON object from array [duplicate] - javascript

This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed 8 months ago.
I have tried splicing my json file using a for loop
JSON file:
[
{
"name":"Billy Jean",
"age":"52",
"sex":"F",
},
{
"name":"Bob Semple",
"age":"32",
"sex":"M",
} there are more....
]
What I have tried (i imported it and called it contactList)
for(let i = 0 ; i < contactList.length ; i++){
if(contactlist.age > 40) {
contactList.splice(i, 1);
}
}
if i run the code and check the output nothing changes in my JSON file

You can create a new array using Array.prototype.filter() combined with Destructuring assignment
Notice that age property it's of type string and should be compared as number using unary plus (+) operator
Code:
const data = [{
"name": "Billy Jean",
"age": "52",
"sex": "F",
},
{
"name": "Bob Semple",
"age": "32",
"sex": "M",
}
]
const result = data.filter(({ age }) => +age > 40)
console.log(result)

Related

Parsing complex object in JavaScript [duplicate]

This question already has answers here:
How to iterate over a JavaScript object?
(19 answers)
Closed 7 months ago.
I have an object as follows
{
"s": "success",
"result": {
"XX-YY-12-33": {
"quantity": "88",
"warehouse_name": "USA Hub"
},
"AD-12-Y6-00": {
"quantity": "99",
"warehouse_name": "USA Hub"
}
}
}
The result object contains multiple objects which actually is the id of an sku
I want to access this each sku but don't have them separately anywhere. Can anyone tell how can I access them?
Does this help?
I've put some comments in the code for further explanation.
const data = {
"XX-YY-12-33": {
"quantity": "88",
"warehouse_name": "USA Hub"
},
"AD-12-Y6-00": {
"quantity": "99",
"warehouse_name": "USA Hub"
}
};
// You can extract only the ids using Object.keys
const dataIds = Object.keys(data);
// Having the ref of the ids you can now iterate over them to extract the info you need per id
// Using array map function for example we can extract all the quantities:
const dataQtys = dataIds.map((id) => Number(data[id].quantity));
// alternatively you can use "Object.entries".
// If you want to sum all quantities you can use array reduce function:
const sum = dataQtys.reduce((res, qty) => res + qty, 0);
console.log('Ids: ', dataIds);
console.log('Quantities: ', dataQtys);
console.log('Sum: ' + sum);
You mean this?
Object.entries and reduce
Had you been clearer, I would have given a more complex answer first time around
const obj = {
"s": "success",
"result": {
"XX-YY-12-33": {
"quantity": "88",
"warehouse_name": "USA Hub"
},
"AD-12-Y6-00": {
"quantity": "99",
"warehouse_name": "USA Hub"
}
}
}
const res = Object.entries(obj.result)
.reduce((acc, [key,{quantity}]) => { // spread the key and extracted quantity from value
acc.keys.push(key); // save the key
acc.quantity.push(+quantity); // save the quantity (unary plus to convert to number)
acc.sum += +quantity; // sum it
return acc;
},{keys:[],quantity:[],sum:0}); // into an initialised object
console.log(res)

Find index of an object in an arrray of objects [duplicate]

This question already has answers here:
How can I get the index of an object by its property in JavaScript?
(22 answers)
Closed 1 year ago.
I have an array that looks like this:
const arr = [
{ "-MrUU6N2pi7aCwJoqCzP": { "name": "test", "brand": "test", "id": 1 } },
{ "-MrUUB4PcPD5G45NGb-y": { "name": "test2", "brand": "test2", "id": 2 } }
]
How do I find the index of the object with the key "-MrUUB4PcPD5G45NGb-y" for example?
You can use findIndex() and look at the Object.keys() for each object in the array to see if the key you want is in that keys array
const arr = [
{"-MrUU6N2pi7aCwJoqCzP":{"name":"test","brand":"test","id":1}},
{"-MrUUB4PcPD5G45NGb-y":{"name":"test2","brand":"test2","id":2}}
],
keyWanted = "-MrUUB4PcPD5G45NGb-y",
idx = arr.findIndex(e => Object.keys(e).includes(keyWanted))
console.log('Index =', idx)

How to pull a property like "customer.gender" from an array of object with map [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 4 years ago.
I am using javascript map to loop through an array of object. Today i have to loop through an array of object which looks like,
averageReport = [
{
"result": 150.54909908933223,
"customer.gender": "Female"
},
{
"result": 150.35230422844595,
"customer.gender": "Male"
}
];
What i tried to get only the "customer.gender",
averageReport
.map(x => console.log(x.customer.gender)
)
I get the error "Cannot read property 'gender' of undefined"
code on stackblitz
Try,
averageReport
.map(x => console.log(x["customer.gender"])
Since you named your key customer.gender you can't use dot-notation to get the value, you have to use bracket notation ([]).
Also mapping to console.log() doesn't make much sense (since console.log() returns undefined, you are creating a new array of undefined when using map() here), just use forEach():
averageReport = [{
"result": 150.54909908933223,
"customer.gender": "Female"
},
{
"result": 150.35230422844595,
"customer.gender": "Male"
}
];
averageReport.forEach(x => console.log(x["customer.gender"]));
If you want to access the property using dot-notation, you have to make customer an object and gender a property of it, like so:
averageReport = [{
"result": 150.54909908933223,
"customer": {
"gender": "Female"
}
},
{
"result": 150.35230422844595,
"customer": {
"gender": "Male"
}
}
];
Use bracket notation for accessing the customer.gender property. Try the following :
var averageReport = [ { "result": 150.54909908933223, "customer.gender": "Female" }, { "result": 150.35230422844595, "customer.gender": "Male" } ];
var result = averageReport.map(x =>x["customer.gender"]);
console.log(result);

Can't seem to delete element in object literal [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 6 years ago.
I have a JSON object literal from which I'm trying to delete an element (let's say apples). I've tried many things, but I just can't seem to get it to work.
var JSON = {
"fruits": [{
"name": "oranges",
"quantity": "3"
},{
"name": "apples",
"quantity": "2"
},{
"name": "bananas",
"quantity": "3"
}
]};
console.log(JSON);
delete JSON.fruits[1];
console.log(JSON);
Calling the above code results in the object being removed, but it looks like then inserts the key before the 3rd object. Have a look at this fiddle. I don't want that to happen.
That's what happens in the Fiddle. But then in my live script however, it looks like it replaces the deleted object with the word null which breaks my script.
I've also tried many variations of .splice() but that seems to be for arrays, rather than object literals.
Any ideas?
You could use Array#splice for the array inside of the object.
delete deletes the object, but you get an undefined element of the array.
var object = { fruits: [{ name: "oranges", quantity: "3" }, { name: "apples", quantity: "2" }, { name: "bananas", quantity: "3" }] };
object.fruits.splice(1, 1);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
JSON.fruits.splice(1, 1); // to remove apples
Knowledge: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Finding JSON path inside object [duplicate]

This question already has answers here:
Convert string in dot notation to get the object reference [duplicate]
(6 answers)
Closed 8 years ago.
How to check in an JSON object, the input path is present or not?
var obj = {
"schemaOne": {
"name": "abc",
"Path": "i.abc",
"count": 5347,
"subFolders": [
]
},
"schemaTwo": {
"name": "cde",
"Path": "i.cde",
"count": 0,
"subFolders": [
{
"name": "efg",
"Path": "",
"count": 0,
"subFolders": [
]
},
{
"name": "hij",
"Path": "i.hij",
"count": 1,
"subFolders": [
]
}
]
}
}
var inputpath = "obj.count";
After doing several research I came across below code. Here in this code, o.Path is known to the user. But I want to modify the code so tat dynamically check obj.count is present in JSON object or not?
function upd(o, path, count) {
if (o.Path == path) {
o.count = count;
} else {
var arr;
if (Array.isArray(o)) arr = o;
else if (o.subFolders) arr = o.subFolders;
else return;
for(var j=0; j < arr.length; j++) {
upd(arr[j], path, count);
}
}
}
Your question isn't very clear, neither the use case. As someone told u, obj is a JavaScript object, not a JSON.
If I understood correctly, you want to check if a path, espressed as string (such as "obj.count") exists in that object.
A very fast but not safe solution (eval is evil and should be avoided almost in every case) could be:
if(eval(inputpath)){
//... do something
}
In alternative, I suggest you to write a function that gets an object and a string (path) as parameter, parses the string path and check if the object contains such path.
Start from here: Accessing nested JavaScript objects with string key

Categories

Resources