How to remove a child object from a JSON object using javascript - javascript

I'm trying to search through a JSON object to find the pet-rock that I want to delete. Here is a simple JSON that I'm working on:
myData.json:
{
"data": [
{
"name": "John",
"age": "25",
"pet-rocks": [
{
"name": "Travis",
"age": "9"
},
{
"name": "Steven",
"age": "5"
},
{
"name": "Oliver",
"age": "7"
}
]
},
{
"name": "Jane",
"age": "25",
"pet-rocks": [
{
"name": "Jesse",
"age": "4"
},
{
"name": "Carol",
"age": "8"
},
{
"name": "Jake",
"age": "7"
}
]
}
]
}
I would like to do a search for "Steven" and remove that pet-rock from the list. Here are the things I've tried:
MyJSFile.js:
const myDataObject = require('./myData.json');
for (let key in myDataObject) {
let value = myDataObject[key];
if (value === "Steven")
{
delete myDataObject[key];
}
//To see if I get the data I want
console.log(key, value);
}
However, my output is strange and I'm not sure how to get to that child node of petrock. It appears that the petrocks are in object form, and I'm not sure how to get to them. here is the ouput of my console below. I assume it didn't get delete as there are still 3 petrock objects in the data.
data [
{
name: 'Robert',
age: '25',
'pet-rocks': [ [Object], [Object], [Object] ]
},
{
name: 'Robert',
age: '25',
'pet-rocks': [ [Object], [Object], [Object] ]
}
]
Any help or suggestions would be greatly appreciated! Thanks!

The pet rock named Steven is not a direct child of myDataObject, so you can't delete it like that. You can loop through the "data" array, rebuilding the "pet-rocks" array for each element. A simple filter to remove any pet rocks named Steven should work.
const myDataObject = {
"data": [
{
"name": "John",
"age": "25",
"pet-rocks": [
{
"name": "Travis",
"age": "9"
},
{
"name": "Steven",
"age": "5"
},
{
"name": "Oliver",
"age": "7"
}
]
},
{
"name": "Jane",
"age": "25",
"pet-rocks": [
{
"name": "Jesse",
"age": "4"
},
{
"name": "Carol",
"age": "8"
},
{
"name": "Jake",
"age": "7"
}
]
}
]
};
myDataObject.data.forEach(d => {
d["pet-rocks"] = d["pet-rocks"].filter(rock => rock.name !== "Steven");
});
console.log(myDataObject);

Related

Creating an object which contains unique item from a nested array

I have an array of objects called employees. I need a solution that will return me a list of groups and respective employees present in the group along with the group properties.
The example is below, I have used an object but the result can also be an array that has a property called groupName within an object. [{groupName:"developer", employees:[],...}..] As long as the response returns a list of groups with their corresponding employees.
Below is the solution I did but I need a solution with a better time complexity that is O(n).
const employees = [
{ "name": "John Doe",
"id": "1",
"groups": [
{ "id": "developerId", "name": "developer", "color": "#fff" },
{ "id": "engineerId", "name": "engineer", "color": "#fff" }
],
"groupId":["developerId", "engineerId"]
},
{ "name": "Jane Doe",
"id": "2",
"groups": [
{ "id": "developerId", "name": "developer", "color": "#fff" },
{ "id": "testerId", "name": "tester", "color": "#fff" }
],
"groupId":["developerId", "testerId"]
}
]
//Solution O(m*n)
let groups = {};
employees.forEach((item) => {
item.groups.forEach((group) => {
if (!groups[group.name]) {
groups[group.name] = {
employees: [item.id],
...group,
};
} else {
groups[group.name].employees = [...groups[group.name].employees, item.id];
}
});
});
//result
{
"developer":{
"id":"developerId",
"employee":[
"1",
"2"
],
"color":"#fff"
},
"engineer":{
"id":"employeeId",
"employee":[
"1",
],
"color":"#fff"
},
"tester":{
"id":"testerId",
"employee":[
"2",
],
"color":"#fff"
}
}
Using Array#reduce and Array#forEach:
const employees = [
{
"name": "John Doe",
"id": "1",
"groups": [
{ "id": "developerId", "name": "developer", "color": "#fff" },
{ "id": "engineerId", "name": "engineer", "color": "#fff" }
],
"groupId": ["developerId", "engineerId"]
},
{
"name": "Jane Doe",
"id": "2",
"groups": [
{ "id": "developerId", "name": "developer", "color": "#fff" },
{ "id": "testerId", "name": "tester", "color": "#fff" }
],
"groupId": ["developerId", "testerId"]
}
];
const groups = employees.reduce((acc, { id: employeeId, groups = [] }) => {
groups.forEach(({ id, name, color }) => {
acc[name] = {
id, color, employee: [...(acc[name]?.employee ?? []), employeeId]
};
});
return acc;
}, {});
console.log(groups);
If you like to add some speed, you could use the old fashioned for statement for iterating, especially of having only a single result object.
This approach does not create an object again and again and uses the already existing objects.
const
employees = [{ name: "John Doe", id: "1", groups: [{ id: "developerId", name: "developer", color: "#fff" }, { id: "engineerId", name: "engineer", color: "#fff" }], groupId: ["developerId", "engineerId"] }, { name: "Jane Doe", id: "2", groups: [{ id: "developerId", name: "developer", color: "#fff" }, { id: "testerId", name: "tester", color: "#fff" }], groupId: ["developerId", "testerId"] }],
result = {};
for (const { id: employeeId, groups } of employees) {
for (const { id, name, color } of groups) {
result[name] ??= { id, color, employee: [] };
result[name].employee.push(employeeId);
}
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comparing 2 objects and making alterations based on Match

I have 2 objects with key-value pairs that should always be identical (match) otherwise I want to modify the value of the key in object #1 to "Some Value - Not available"
Here are my 2 objects:
Object #1
[
{
"name": "John",
"age": "12",
"id": 1
},
{
"name": "tina",
"age": "19",
"id": 2
}]
Object #2 ( name checker)
[
{
"value": "tina"
},
{
"value": "Trevor"
},
{
"value": "Donald"
},
{
"value": "Elon"
},
{
"value": "Pamela"
},
{
"value": "Chris"
},
{
"value": "Jackson"
}
]
I would like to find out if name in Object #1 is found in Object #2 and if it is not found, add " - not available"
e.i
[
{
"name": "John - not available",
"age": "12",
"id": 1
},
{
"name": "tina",
"age": "19",
"id": 2
}
]
Important Note: I'm using ES5 --- not ES6
This should work in ES5
object1.forEach(function(person) {
var found = false;
Object.keys(object2).forEach(function(key) {
if (person.name === object2[key].value) {
found = true;
}
});
if (!found) {
person.name = person.name + " - not available";
}
});

Find object by property in JSON array

I have problem with get string in JSON data. Format as below:
[
{
"name": "Alice",
"age": "20"
},
{
"id": "David",
"last": "25"
},
{
"id": "John",
"last": "30"
}
]
Sometime it changes position together, John from 3rd place go to 2nd place:
[
{
"name": "Alice",
"age": "20"
},
{
"name": "John",
"age": "30"
},
{
"name": "David",
"age": "25"
}
]
If i use data[3].age to get John's age, and data change position, I will get David's age.
Is there any method I can use to find the object with name David and get the age value?
You can use array.find() method as,
var myArray = [
{
"name": "Alice",
"age": "20"
},
{
"name": "John",
"age": "30"
},
{
"name": "David",
"age": "25"
}
];
//Here you are passing the parameter name and getting the age
//Find will get you the first matching object
var result = myArray.find(t=>t.name ==='John').age;
console.log(result);
It's better to use array.filter() (better browser support)
myArray.filter(function(el){return el.name == "John"})[0].age

How to merge children in multiple JSON objects?

I have the following JavaScript object
[
{
"familyName": "Smith",
"children": [
{ "firstName": "John" },
{ "firstName": "Mike" }
]
},
{
"familyName": "Williams",
"children": [
{ "firstName": "Mark" },
{ "firstName": "Dave" }
]
},
{
"familyName": "Jones",
"children": [
{ "firstName": "Mary" },
{ "firstName": "Sue" }
]
}
]
I’d like to create an array of all children i.e.
[
{ "FirstName": "John" },
{ "FirstName": "Mike" },
{ "FirstName": "Mark" },
{ "FirstName": "Dave" },
{ "FirstName": "Mary" },
{ "FirstName": "Sue" }
]
I am using jQuery.
I have looked at posts that describe merging or concatenating arrays but not those of child arrays: e.g. Merge/flatten an array of arrays in JavaScript?
I believe I could loop through the families and add the children arrays but suspect that there is a 'one-liner' for this?
I tested in the console:
//The families(duh)
const families = [
{
"familyName": "Smith",
"children": [
{ "firstName": "John" },
{ "firstName": "Mike" }
]
},
{
"familyName": "Williams",
"children": [
{ "firstName": "Mark" },
{ "firstName": "Dave" }
]
},
{
"familyName": "Jones",
"children": [
{ "firstName": "Mary" },
{ "firstName": "Sue" }
]
}
]
//Just flatten the children:
var children = [].concat.apply([], families.map(family => family.children));
//Outputs
console.log(children);
A solution without jQuery would be to use reduce to extract children from their families (sounds a bit rough, sorry for that).
families.reduce(function(list, family){
return list.concat(family.children);
}, []);
You can do this by using $.map:
var a = [
{
"familyName": "Smith",
"children": [
{ "firstName": "John" },
{ "firstName": "Mike" }
]
},
{
"familyName": "Williams",
"children": [
{ "firstName": "Mark" },
{ "firstName": "Dave" }
]
},
{
"familyName": "Jones",
"children": [
{ "firstName": "Mary" },
{ "firstName": "Sue" }
]
}
]
console.log($.map(a, function(it){
return it.children;
}));
// Or ES6
$.map(a, it => it.children);
Result:
[
{
"firstName":"John"
},
{
"firstName":"Mike"
},
{
"firstName":"Mark"
},
{
"firstName":"Dave"
},
{
"firstName":"Mary"
},
{
"firstName":"Sue"
}
]
Try with Array#forEach method .then push the children object with new array
var families = [ { "familyName": "Smith", "children": [ { "firstName": "John" }, { "firstName": "Mike" } ] }, { "familyName": "Williams", "children": [ { "firstName": "Mark" }, { "firstName": "Dave" } ] }, { "familyName": "Jones", "children": [ { "firstName": "Mary" }, { "firstName": "Sue" } ] } ]
var children = [];
families.forEach(family => family.children.forEach(child => children.push(child)));
console.log(children);

How to add a name for each element of a list in Jackson

Is it possible to set a name for each element of a list in JSON using JACKSON?
For example, I have the following JSON:
{"result": [
{
"name": "ABC",
"age": "20"
},{
"name": "DEF",
"age": "12"
}
]}
But I need this:
{"result": [
person: { // << this is the name
"name": "ABC",
"age": "20"
},
person: {
"name": "DEF",
"age": "12"
}
]}
Thanks to everybody!
UPDATE
Hi people!
I made a mistake! The correct form is the following:
{"result": [
{
person: { // << this is the name
"name": "ABC",
"age": "20"
}
},
{
person: {
"name": "DEF",
"age": "12"
}
}
]}
In plain Javascript, you could use Array#map and return a new object with person property.
var object = { result: [{ name: "ABC", age: "20" }, { name: "DEF", age: "12" }] };
object.result = object.result.map(function (a) {
return { person: a };
});
console.log(object);

Categories

Resources