How can I create an json format in javascript
var data = [
{
label: 'node1',
children: [
{ label: 'child1' },
{ label: 'child2' }
]
},
{
label: 'node2',
children: [
{ label: 'child3' }
]
}
]
I can add the 'node' using data.push, but how to proceed with childrens?
Thank's!
First off, there is no such thing as a JSON array. You are working with an array. JSON is a way to transfer data between systems.
You have an array called data that you need to push an object into...
so something like:
data.push({
label: 'node3',
children: [
{ label: 'child3' },
{ label: 'child3' }
]
});
Now.. you've got a problem at this point, because you are duplicating the label property, which is not allowed under ES5 strict mode.
Related
I have a object which is created by groupBy function.
const productOptions = {
color: [
{ id: 1, type: "color", name: "red" },
{ id: 2, type: "color", name: "orange" },
{ id: 3, type: "color", name: "yellow" },
],
size: [
{ id: 4, type: "size", name: "sm" },
{ id: 5, type: "size", name: "md" },
{ id: 6, type: "size", name: "lg" },
{ id: 7, type: "size", name: "xl" },
],
};
To display product options by type, I hardcoded it like below.
<ProductOption productOptionType={"color"} productOptions={productOptions.color} />
<ProductOption productOptionType={"size"} productOptions={productOptions.size} />
In the future, weight, accessory, and more will be added to type.
I hate this static structure. Is there a way to display it dynamically using productOptions object at once??
I tried with .map(), But object's keys are not accessible.
I also tried with for-in loop, It doesn't render well.
How can I solve this???
Use Object.keys to loop over keys, then you can dynamically render as many as you want. So render this:
Object.keys(productOptions).map(key => (
<ProductOption productOptionType={key} productOptions={productOptions[key]} />
))
You could use Object.keys here
Object.keys(productOptions).map((item)=>(
<ProductOption productOptionType={item} productOptions={productOptions[item]} />
)
What's the best way to loop through a javascript array, looking for elements of interest and, for each one, make the elements in between "children" of the preceding element of interest?
Essentially, I want to go from flat data that looks like:
[
{
value: "foo",
type: "header!"
},
{
value: "bar",
type: "normal"
},
{
value: "bar",
type: "normal"
},
{
value: "foo",
type: "header!"
},
{
value: "bar",
type: "normal"
}
]
To something more like:
[
{
value: "foo",
type: "header!",
children: [
{
value: "foo",
type: "normal"
},
{
value: "bar",
type: "normal"
}
]
},
{
value: "bar",
type: "header!",
children: [
{
value: "foo",
type: "normal"
}
]
},
]
I think that Array.reduce is what I need here, but I'm struggling with exactly how to make it do what I need.
So far I've tried code that looks like:
const nestedArray = flatArray.map(el => {
if(el.type === "header!") return {
type: el.type,
children: []
}
})
Just loop, check the type field and push it either in the main array or in the children of the last header:
data = [
{value: "foo", type: "header!"},
{value: "bar", type: "normal"},
{value: "bar", type: "normal"},
{value: "foo", type: "header!"},
{value: "bar", type: "normal"}
]
let tree = [], last
for (let elem of data) {
if (elem.type === 'header!')
tree.push(last = {...elem, children: []})
else
last.children.push(elem)
}
console.log(tree)
As a general advice, try to avoid functions like map and reduce when manipulating complex data structures. They are far less readable, harder to reason about and much slower than for..of loops.
Consider this example. I am trying to move to first element of 2-D ARRAY which contains two array items and use spread operator until I get text inside the inner most array.
let arr = [
[ {
type: 'paragraph',
children: [{ text: 'First line.' }],
},
{
type: 'paragraph',
children: [{ text: 'Second.' }],
}
],[
{
type: 'paragraph',
children: [{ text: 'Third.' }],
},
{
type: 'paragraph',
children: [{ text: 'Fourth.' }],
}
]
]
//const newArr = [...arr[0]] // more logic
//result to ['first line','Second.']
JS Fiddle to test the array
I dont think the spread operator will be of any help here, but consider this:
let arr = [
[ {
type: 'paragraph',
children: [{ text: 'First line.' }],
},
{
type: 'paragraph',
children: [{ text: 'Second.' }],
}
],[
{
type: 'paragraph',
children: [{ text: 'Third.' }],
},
{
type: 'paragraph',
children: [{ text: 'Fourth.' }],
}
]
]
let result1 = [];
arr.flat().forEach(element => result1.push(element.children[0].text));
console.log("Result1:", result1);
// or just group the children from arr[0] together:
let result2 = [];
arr[0].forEach(element => result2.push(element.children[0]));
console.log("Result2:", result2);
In my Vue project, I'm doing an API call to my Laravel (nova) backend, the data is returned as follows.
As you can see the data is an array, which contains an array of objects. Each array represents a record, while each object represents a field in that record.
There is the possibility that a record has unnecessary data.
const data = [
[
{
attribute: 'id',
value: 1,
extra: "not needed data"
},
{
attribute: 'title',
value: 'The Title',
extra: "not needed data"
},
],
[
{
attribute: 'id',
value: 2
},
{
attribute: 'title',
value: 'The Other Title'
},
],
]
I'm wondering how I can use Javascript to flatten this out so it becomes
const data = [
{id: 1, title: 'The Title'},
{id: 2, title: 'The Other Title'}
]
What I've tried
I've tried using a combination of map and filter, but the results don't even come close.
You could use map with reduce, to build an object using only the attribute and value, ignoring all other properties:
const data = [
[
{
attribute: 'id',
value: 1,
extra: "not needed data"
},
{
attribute: 'title',
value: 'The Title',
extra: "not needed data"
},
],
[
{
attribute: 'id',
value: 2
},
{
attribute: 'title',
value: 'The Other Title'
},
],
]
console.log(data.map(a => a.reduce((a, o) => (a[o.attribute] = o.value, a), {})))
lets say i want to start with empty value of variable data, how can to achieve this result with javascript using push method:
var data = [
{
label: 'node1',
children: [
{ label: 'child1' },
{ label: 'child2' }
]
},
{
label: 'node2',
children: [
{ label: 'child3' }
]
}
];
i have tried:
data.push("label: nodel", "children:"+ ['child1', 'child2']);
looking at code above i need to insert one element that will be linked with list of childs. Can someone help me achieve this.. i would be very grateful.
Best regards.
Is this what you mean?
var object1 = {
label: 'node1',
children: [
{ label: 'child1' },
{ label: 'child2' }
]
};
var data = new Array();
data.push(object1);
OR
data.push({ label: 'node1', children: [ { label: 'child1' }, { label: 'child2' } ] });
EDITED TO SHOW YOSHIS VERSION ASWELL