How to append <li> to each array? - javascript

My head was overheated today.. I need help with my code. My English is not so good, so it's hard to explain my issue. So I put problem in HTML what kind of style I need to get from JS. Added things.json file as example, and added JS code.
<!-- What I'm getting: -->
<h2>Table</h2>
<ul>
<li>brown, black, white</li>
</ul>
<!-- What I need to get: -->
<h2>Table</h2>
<ul>
<li>brown</li>
<li>black</li>
<li>white</li>
</ul>
There's example of things.json file:
[
{
"thing": "table",
"color": [
"brown",
"black",
"white"
]
}
{
"thing": "chair",
"color": [
"yellow",
"black",
"blue"
]
}
{
"thing": "bed",
"color": [
"red",
"blue",
"green"
]
}
]
There is example of my function:
const ENDPOINT = 'things.json'
async function getThing(url) {
const resp = await fetch(url)
const data = await resp.json()
data.forEach(appendToHtml) return data
}
getThing(ENDPOINT).then((value) => { console.log('getThings', value) })
function appendToHtml(data) {
const divEl = document.createElement('div')
const h2El = document.createElement('h2')
const liEl = document.createElement('li')
h2El.textContent = data.thing
liEl.textContent = data.color
outputEl.append(divEl)
divEl.append(h2El)
divEl.append(liEl)
return divEl
}

Assuming your json is an array of objects (with colors) you would need 2 levels of loops. One for every item (object) in the array. The other for each object to build the list from its colors (that's also an array).
var arr = [{
"thing": "table",
"color": [
"brown",
"black",
"white"
]
}, {
"thing": "chair",
"color": [
"yellow",
"black",
"blue"
]
}, {
"thing": "bed",
"color": [
"red",
"blue",
"green"
]
}];
var outputEl = document.body;
function appendToHtml(data) {
const divEl = document.createElement('div')
const h2El = document.createElement('h2')
const list_container = document.createElement('div')
h2El.textContent = data.thing
outputEl.append(divEl)
divEl.append(h2El)
divEl.append(list_container)
list_container.innerHTML = appendToList(data.color);
return divEl
}
function appendToList(colors) {
return "<ul>" + colors.map(color=>`<li>${color}</li>`).join("\n") + "</ul>"
}
arr.forEach(function(obj) {
appendToHtml(obj)
})
<body>
</body>

Related

Array item using its own parent object index as its value?

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)

Modify all object inside an array of objects

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']));

Traverse Array of objects to generate d3 Sankey Chart data

This input (tree-like structure) has to be formatted to a particular format to draw a d3 sankey diagram chart.
let unformattedJson = [
{
"key": "a1",
"value": 30,
"buckets": [
{
"key": "a2",
"value": 10
},
{
"key": "b2",
"value": 20
}
]
},
{
"key": "b1",
"value": 70,
"buckets": [
{
"key": "b2",
"value": 40
},
{
"key": "c2",
"value": 30
}
]
}
]
Expected output I need to generate is:
{
"nodes": [
{"nodeId":0,"name":"a1"},
{"nodeId":1,"name":"a2"},
{"nodeId":2,"name":"b2"},
{"nodeId":3,"name":"b1"},
{"nodeId":4,"name":"c2"}
],
"links": [
{"source":0,"target":1,"value":10},
{"source":0,"target":2,"value":20},
{"source":3,"target":2,"value":40},
{"source":3,"target":4,"value":30}
]
}
My approach for the solution. I made two functions to calculate node and links. For nodes, I made a recursive functions to get all the unique keys and assigned a id for each keys. And I made another functions to get all the relationship between the keys.
let makeNodeObj = function(orObj, index){
let obj = {};
obj.nodeId = index;
obj.name = orObj;
return obj;
}
var getUniqueKeys = (old, arr)=>{
let toRet = old;
arr.forEach((data,index)=>{
if(toRet.indexOf(data.key)<0){ //remove duplicates
toRet.push(data.key);
}
if(data.buckets !== undefined && data.buckets.length>0){
getUniqueKeys(toRet, data.buckets);
}
});
return toRet;
}
let uniqueKeys = getUniqueKeys([],unformattedJson);
let nodes = uniqueKeys.map((data,index)=>{
return makeNodeObj(data,index);
});
let getNodeId = function(nodes, key){
let node = nodes.find((data)=>{
return data.name == key
});
return node.nodeId;
}
let links = [];
unformattedJson.map((data)=>{
let sourceId = getNodeId(nodes, data.key);
if(data.buckets.length>0){
data.buckets.map((data2)=>{
let targetId = getNodeId(nodes,data2.key);
let linkObj = {};
linkObj.source = sourceId;
linkObj.target = targetId;
linkObj.value = data2.value;
links.push(linkObj);
})
}
});
console.log({
nodes, links
});
My solution will only work if there are only one level-deep buckets. How to achieve this for multiple nested buckets inside child?
I made a recursive approach for generate the expected output. Associations between a key and his generated id are keep with a Map. The approach uses the idea of traversing the tree with Deep First Search algorithm.
let unformattedJson = [
{
"key": "a1",
"value": 30,
"buckets": [
{
"key": "a2",
"value": 10,
"buckets": [
{"key": "a3", "value": 99}
]
},
{"key": "b2", "value": 20}
]
},
{
"key": "b1",
"value": 70,
"buckets": [
{"key": "b2", "value": 40},
{"key": "c2", "value": 30}
]
}
];
const getData = (input, visited=new Map(), parent, nodes=[], links=[]) =>
{
input.forEach(x =>
{
// Add node into the node list, if not visited previosuly.
if (!visited.has(x.key))
{
let currId = nodes.length;
nodes.push({nodeId: currId, name: x.key});
visited.set(x.key, currId);
}
// If a parent node exists, add relation into the links list.
if (parent)
{
// Note, we use the "Map" to get the ids.
links.push({
source: visited.get(parent.key),
target: visited.get(x.key),
value: x.value
});
}
// Traverse (if required) to the next level of deep.
if (x.buckets)
getData(x.buckets, visited, x, nodes, links)
});
return {nodes: nodes, links: links};
}
console.log(getData(unformattedJson));

Reading only the first value in JavaScript

I am trying to add the below body to JSON. But I only see one value is being added.
json = { "Myname":"Nate", }
Adding the below code:
Body = Myproperty: [{
"vehicle": "car",
"color": "Red"
}, {
"name": "van",
"color": "white"
}, {
"name": "Truck",
"color": "Blue"
}]
Here is the code I am using:
for (var i = 0; i < Myproperty.length; i++) {
json.mycarname = Body.Myproperty[i].name;
json.mycolor = Body.Myproperty[i].color;
}
The end result should look like this:
{
"Myname": "Nate",
mycarname: "car",
"mycolor": "Red"
},
{
"Myname": "Nate",
mycarname: "van",
"mycolor": "white"
},
{
"Myname": "Nate",
mycarname: "Truck",
"mycolor": "Blue"
}
I guess you want to do something like this:
var myName = "Nate";
var Body = [{
"name": "car",
"color": "Red"
},
{
"name": "van",
"color": "white"
},
{
"name": "Truck",
"color": "Blue"
}
]
var json = [];
for (var i = 0; i < Body.length; i++) {
json.push({
"Myname": myName,
"mycarname": Body[i].name,
"mycolor": Body[i].color
});
}
console.log(json)
The idea is to loop over the entries you want to add and push them into the json array.

how to push array value to another array object value javascript

I've data response like this
{
"data": {
"product": {
"colors": ["#3498db", "#00ccff"],
"items": [
{
"label": "Phone",
"value": "23.00"
},
{
"label": "Notebook",
"value": "3.00"
}
]
}
}
}
and then i want push the colors inside items
expected: items have three(3) variable each of index
items: [
{
label: phone,
value: 23.00,
color: #3498db
}
]
i've try using push and concat but i got error "Cannot read property 'data' of undefined"
here my code
generaliseData(dashboardC) {
let genData = Object.assign({}, dashboardC)
if (genData.product.items.length > 0) {
for (let i of genData.product.items) {
i.value = parseInt(i.value)
for (let j of genData.product.colors) {
i = i.push(j)
}
}
console.log(genData)
}
}
You can use map to iterate through your list, expect to have the length of colors equal the length of item
const response = {
"data": {
"product": {
"colors": ["#3498db", "#00ccff"],
"items": [
{
"label": "Phone",
"value": "23.00"
},
{
"label": "Notebook",
"value": "3.00"
}
]
}
}
};
function addColorToItem(response) {
const product = response.data.product;
const colors = product.colors;
const items = product.items;
return items.map((item, index) => {
item.color = colors[index];
return item;
})
}
console.log(addColorToItem(response));
You could iterate items and assign a color.
var response = { data: { product: { colors: ["#3498db", "#00ccff"], items: [{ label: "Phone", value: "23.00" }, { label: "Notebook", value: "3.00" }] } } },
temp = response.data.product;
temp.items.forEach((o, i) => o.color = temp.colors[i]);
console.log(response);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use a simple forEach() loop for that result:
var data = {
"product": {
"colors": ["#3498db", "#00ccff"],
"items": [{
"label": "Phone",
"value": "23.00"
},
{
"label": "Notebook",
"value": "3.00"
}
]
}
};
data.product.items.forEach((item, index) => item.color = data.product.colors[index]);
console.log(data);

Categories

Resources