How to convert array of objects to object containing that data - javascript

I need to convert an array of objects to an object of objects in JavaScript.
The ID of the book should be the ID of each object from the array.
Array that I have:
[{
"author" : "cccc",
"catid" : 22,
"id" : 25,
"logo" : "logo",
"name" : "Book c",
"size" : 84777
}, {
"author" : "ddd",
"catid" : 22,
"id" : 26,
"logo" : "logo",
"name" : "Book d",
"size" : 105139
}]
Object that I need:
{
"25":{
"author" : "bbbb",
"catid" : 22,
"logo" : "logo",
"name" : "Book b",
"size" : 73386
},
"26":{
"author" : "cccc",
"catid" : 22,
"logo" : "logo",
"name" : "Book c",
"size" : 84777
}}

You could use reduce:
const arr = [{
"author": "aaaa",
"catid": 22,
"id": 23,
"name": "Book a",
"size": 56658
}, {
"author": "bbbb",
"catid": 22,
"id": 24,
"logo": "logo",
"name": "Book b",
"size": 73386
}, {
"author": "cccc",
"catid": 22,
"id": 25,
"logo": "logo",
"name": "Book c",
"size": 84777
}, {
"author": "ddd",
"catid": 22,
"id": 26,
"logo": "logo",
"name": "Book d",
"size": 105139
}]
const obj = arr.reduce((a, {id, ...obj}) => (a[id] = obj, a), {})
console.log(obj)
Reduce will loop over each object in the array, and the code inside will append the object to the accumulator, by id and then return that as an object.

The problem with the approach given above is it is limited to objects where the new object key is going to be id. Lets abstract this so the function is re-usable in all situations!
As stated above in your query, you want to convert a JSON Array called BookArray into a JSON Object called BookObject as follows.
const bookArray = [{
"author" : "cccc",
"catid" : 22,
"id" : 25,
"logo" : "logo",
"name" : "Book c",
"size" : 84777
}, {
"author" : "ddd",
"catid" : 22,
"id" : 26,
"logo" : "logo",
"name" : "Book d",
"size" : 105139
}]
Your resulting bookObject after processing should look like this.
const bookObject = {
"25":{
"author" : "bbbb",
"catid" : 22,
"logo" : "logo",
"name" : "Book b",
"size" : 73386
},
"26":{
"author" : "cccc",
"catid" : 22,
"logo" : "logo",
"name" : "Book c",
"size" : 84777
}}
const arrayToObject = (array, keyField) =>
array.reduce((obj, item) => {
obj[item[keyField]] = item
return obj
}, {})
const bookObject = arrayToObject(bookArray, "id")
console.log(bookObject[idToSelect])
The above code now accepts a keyField which allows us to use this function to convert any array of objects. Not just those who have the field id. This is important for reusability of our code.

Related

C#/Javascript: How to convert JSON string contains parents-child array into multiple parents? [duplicate]

This question already has answers here:
Map and reduce array of objects with a children array down to array of children with parent's id
(3 answers)
Closed 1 year ago.
I'd like to split parents-child array into multiple parents with one child. The JSON string as below:
[{
"Father-Name" : "Jack",
"Mother-Name" : "Rose",
"Children": [{ "Name" : "Lmao" }, {"Name" : "Lol"}]
},
{
"Father-Name" : "Donald",
"Mother-Name" : "Melissa",
"Children": null
}]
and my desired output:
[{
"Father-Name" : "Jack",
"Mother-Name" : "Rose",
"Children": { "Name" : "Lmao" }
},
{
"Father-Name" : "Jack",
"Mother-Name" : "Rose",
"Children": {"Name" : "Lol"}
},
{
"Father-Name" : "Donald",
"Mother-Name" : "Melissa",
"Children": null
}]
I did some searching but there's no matching for this.
The answer is in this link solution. Thanks to #JLRishe
I only modified a null check.
var data = [{
"Father" : "Jack",
"Mother" : "Rose",
"Children": [{ "Name" : "Lmao" }, {"Name" : "Lol"}]
},
{
"Father" : "Donald",
"Mother" : "Melissa",
"Children": null
}]
var result = data.map(d => d.Children!== null ? d.Children.map(c => ({"Father": d.Father,"Mother": d.Mother, Children: {...c}})) : d).flat();
console.log(result);

In an array of Objects, how do I return all Objects by property in React?

What I want to do is create a multi-checkbox filter. So when I click the checkbox titled 'Accessories', it returns all items that contain the value 'Accessories' under the property 'type'.
But before I do that I need to understand how to manipulate and traverse my data properly.
I have a json file named products that contains all of the products of a store and it looks like so.
[
{
"id" : 1,
"name" : "Net and Post Set",
"type" : "Accessories",
"price" : 35,
"desc" : "It's a solid blade. 11111"
},{
"id" : 10,
"name" : "Platinum 3* Balls (Bag of 36)",
"type" : "Balls",
"price" : 12,
"desc" : "It's a solid blade. 11111"
},{
"id" : 22,
"name" : "Galaxy MC2",
"type" : "Blades",
"category" : "Composite",
"price" : 60,
"desc" : "It's a solid blade. 11111"
},
{
"id" : 23,
"name" : "Oversized Carbon fl, st",
"type" : "Blades",
"category" : "Composite",
"price" : 32,
"desc" : "It's a solid blade. 11111"
}
]
But when i print it out in the console it is a mess.
Firstly, it prints as an array within an array. Secondly, that nested array has the key '0' and the rest of the values also have keys.
Lets assume im passing products.json to a function. In order to print the array without the leading zero to the console I have to call console.log(props.products[0]).
But my question is how do I reference the "type" property of all of the Objects in props.products[0]. props.products[0].type returns undefined. Which means I would have to step through each and every item?
You can use Array#map with destructuring.
const props = {
products: [
[{ "id": 1, "name": "Net and Post Set", "type": "Accessories", "price": 35, "desc": "It's a solid blade. 11111" }, { "id": 10, "name": "Platinum 3* Balls (Bag of 36)", "type": "Balls", "price": 12, "desc": "It's a solid blade. 11111" }, { "id": 22, "name": "Galaxy MC2", "type": "Blades", "category": "Composite", "price": 60, "desc": "It's a solid blade. 11111" }, { "id": 23, "name": "Oversized Carbon fl, st", "type": "Blades", "category": "Composite", "price": 32, "desc": "It's a solid blade. 11111" } ]
]
};
const types = props.products[0].map(({type})=>type);
console.log(types);

How to add multiple values in JSON object and get an updated json file

I have the following JSON file
var info = [{
"name" : "john",
"address" : "32 street, london",
"contact" : 123456
},{
"name" : "jeyy",
"address" : "51 street, new york",
"contact" : 987654321,
"gender" : "male"
},{
"name" : "robert",
"address" : "14th street, birmingham",
"contact" : 456123789,
"gender" : "male"
},{
"name" : "carlos",
"address" : "89th street, manchester",
"contact" : 23456
},{
"name": "johnny",
"address": "6th street, Washington",
"contact": 23456
},{
"name": "jack",
"address": "4th street, VA",
"contact": 23456,
"gender": "male"
}
];
As you can see I am missing "gender" = "male" object in some of the array. How can I add them in the missing object and not add them in an object which already have.
Also how would I get a new updated file.
Here I use forEach() to iterate through the array and check each object if it has a value in gender property. If it doesn't then give it a value "male".
var info = [{
"name" : "john",
"address" : "32 street, london",
"contact" : 123456
},{
"name" : "jeyy",
"address" : "51 street, new york",
"contact" : 987654321,
"gender" : "male"
},{
"name" : "robert",
"address" : "14th street, birmingham",
"contact" : 456123789,
"gender" : "male"
},{
"name" : "carlos",
"address" : "89th street, manchester",
"contact" : 23456
},{
"name": "johnny",
"address": "6th street, Washington",
"contact": 23456
},{
"name": "jack",
"address": "4th street, VA",
"contact": 23456,
"gender": "male"
}
];
info.forEach(i => {
if(!i.gender) i.gender = "male";
});
console.log(info);
You can use .hasOwnProperty on that object to find out which object don't have property gender and iteratively add it and write back into the file again!
Here's a code snippet to help you get started.
const fs = require('fs');
const util = require('util');
// Promisify fs api(s)
const readFileAsync = util.promisify(fs.readFile);
const writeFileAsync = util.promisify(fs.writeFile);
// IIFE to read the file, find the objects which has missing properties, add them and write them back
(async function() {
try {
const fileContents = await readFileAsync('data.json');
const fileData = JSON.parse(fileContents);
const remainingData = fileData.filter(x => !x.hasOwnProperty('gender'));
remainingData.forEach(x => x.gender = 'Male');
await writeFileAsync('data.json', JSON.stringify(fileData, null, 4));
} catch(err) {
console.log(`Failed because: {err}!`)
}
})();
This will solve-
var info = [{
"name" : "john",
"address" : "32 street, london",
"contact" : 123456
},{
"name" : "jeyy",
"address" : "51 street, new york",
"contact" : 987654321,
"gender" : "male"
},{
"name" : "robert",
"address" : "14th street, birmingham",
"contact" : 456123789,
"gender" : "male"
},{
"name" : "carlos",
"address" : "89th street, manchester",
"contact" : 23456
},{
"name": "johnny",
"address": "6th street, Washington",
"contact": 23456
},{
"name": "jack",
"address": "4th street, VA",
"contact": 23456,
"gender": "male"
}
];
info.forEach((e)=>{
var t=Object.keys(e);
if(t.indexOf('gender')==-1)
e.gender='male';
})
console.log(info);

JS Object Array Remove last empty element

I have that javascript object :
MyObject = [
{
"name" : "aaa",
"firstname" : "aaaaa"
},
{
"name" : "bbb",
"firstname" : "bbbb"
},
{
"name" : "cccc",
"firstname" : "" <--------- firstname is empty, but the element is not in the last
},
{
"name" : "ddd",
"firstname" : "dddd"
},
{
"name" : "eeee",
"firstname" : "" <--------- firstname is empty
},
{
"name" : "fffff",
"firstname" : "" <--------- firstname is empty
},
]
I want to delete the lastest lines that have "firstname" empty ... (a sort of trim) ... i dont want to remove all lines that have "firstname" empty... but just who are in the latestes lines. (that are in the bottom)
So, the result will be :
MyObject = [
{
"name" : "aaa",
"firstname" : "aaaaa"
},
{
"name" : "bbb",
"firstname" : "bbbb"
},
{
"name" : "cccc",
"firstname" : ""
},
{
"name" : "ddd",
"firstname" : "dddd"
}
]
Thank you
You can pop of at the end of the array as long as the firstname is empty
var MyObject = [{
"name": "aaa",
"firstname": "aaaaa"
}, {
"name": "bbb",
"firstname": "bbbb"
}, {
"name": "cccc",
"firstname": ""
}, {
"name": "ddd",
"firstname": "dddd"
}, {
"name": "eeee",
"firstname": ""
}, {
"name": "fffff",
"firstname": ""
}];
for (var i=MyObject.length;i--;) if (MyObject[i].firstname==="") MyObject.pop(); else break;
console.log(MyObject)
.as-console-wrapper {max-height: 100%!important; top: 0!important;}
Try this:
var MyObject = [
{
"name" : "aaa",
"firstname" : "aaaaa"
},
{
"name" : "bbb",
"firstname" : "bbbb"
},
{
"name" : "cccc",
"firstname" : ""
},
{
"name" : "ddd",
"firstname" : "dddd"
},
{
"name" : "eeee",
"firstname" : ""
},
{
"name" : "fffff",
"firstname" : ""
}
];
var i = MyObject.length;
while(true) {
if (!MyObject[--i].firstname) {
MyObject.pop();
} else {
break;
}
}
console.log(MyObject);

D3 tree/hierachical related data between nodes

I am working on a d3 project at the moment, and I am trying to map out a hierachical tree to show people and who they are responsible for. Basically I can user A and user B and they can each be responsible for the same person.
Currently to highlight this in my JSON data that builds the visualisation I am repeating data, is there away to not repeat data and use the same data point when 2 or more people are responsible for the same person?
Here is my JSfiddle example
My Hierachical Visualisation
You will see here that, Raymond Reddington & Donald Ressler have cross over between some of their responsibilites, I am repeating the data which seems inefficient, is there a better way, here is my JSON.
[
{
"name" : "Company Name",
"parent" : null,
"children": [
{
"name" : "Raymond Reddington",
"parent" : "Cherry Tree Lodge",
"children" : [
{
"name" : "Debe Zuma",
"parent" : "Raymond Reddington",
},
{
"name" : "Tom Keen",
"parent" : "Raymond Reddington",
},
{
"name" : "Aram Mojtabai",
"parent" : "Raymond Reddington",
}
]
},
{
"name" : "Elizabeth Keen",
"parent" : "Cherry Tree Lodge",
"children" : [
{
"name" : "Samar Navabi",
"parent" : "Elizabeth Keen",
},
{
"name" : "Meera Malik",
"parent" : "Elizabeth Keen",
},
{
"name" : "Mr. Kaplan",
"parent" : "Elizabeth Keen",
},
{
"name" : "Reven Wright",
"parent" : "Elizabeth Keen",
}
]
},
{
"name" : "Donald Ressler",
"parent" : "Cherry Tree Lodge",
"children" : [
{
"name" : "Matius Solomon",
"parent" : "Donald Ressler",
"size" : 3938
},
{
"name" : "Peter Kotsiopulos",
"parent" : "Donal Ressler",
"size" : 3938
},
{
"name" : "Tom Keen",
"parent" : "Raymond Reddington",
"size" : 3938
},
{
"name" : "Aram Mojtabai",
"parent" : "Raymond Reddington",
"size" : 3938
}
]
},
{
"name" : "Harold Cooper",
"parent" : "Cherry Tree Lodge",
"children" : [
{
"name" : "Samar Navabi",
"parent" : "Elizabeth Keen",
"size" : 3938
},
{
"name" : "Meera Malik",
"parent" : "Elizabeth Keen",
"size" : 3938
}
]
}
]
}
]
This website details a method of converting flat data to the hierarchical data required by d3 http://www.d3noob.org/2014/01/tree-diagrams-in-d3js_11.html
They explain it well too. As the author notes it is originally based on https://stackoverflow.com/a/17849353/1544886
I have copied and pasted their website's example below:
var data = [
{ "name" : "Level 2: A", "parent":"Top Level" },
{ "name" : "Top Level", "parent":"null" },
{ "name" : "Son of A", "parent":"Level 2: A" },
{ "name" : "Daughter of A", "parent":"Level 2: A" },
{ "name" : "Level 2: B", "parent":"Top Level" }
];
will map to:
var treeData = [
{
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A",
"parent": "Top Level",
"children": [
{
"name": "Son of A",
"parent": "Level 2: A"
},
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level"
}
]
}
];
via:
var dataMap = data.reduce(function(map, node) {
map[node.name] = node;
return map;
}, {});
var treeData = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child array if it doesn't exist
(parent.children || (parent.children = []))
// add node to child array
.push(node);
} else {
// parent is null or missing
treeData.push(node);
}
});
You could extend that further replacing with Ids and using a second normalised array for the lookup:
[{
"id": 0,
"name": "Cherry Tree Lodge"
},{
"id": 1,
"name": "Tom Keen"
},{
"id": 2,
"name": "Debe Zuma"
}]
Also please note that your json data is not strictly valid, you have extra commas.

Categories

Resources