Conversion of JSON String to add parent - javascript

How can I change this
return {
businessSummary: d[0].GeneralInformation.BusinessSummary,
businessUrl: d[0].GeneralInformation.WebSites.HomePage
};
to show output which is like this. Just want to add a parent data node on top
At the moment its like this

You are returning an object with the properties businessSummary and businessUrl at the moment. What you want to do is to return an object with the property data which contains the object with your other properties. Like this:
return { data: {
businessSummary: d[0].GeneralInformation.BusinessSummary,
businessUrl: d[0].GeneralInformation.WebSites.HomePage
}};

Related

How to get first element of array inside an object

I have an object that looks like this
const array_eps = {
episode3: ["https:\/\/www.youtube.com\/embed\/kzZ6KXDM1RI","https:\/\/www.youtube.com\/embed\/T8y_RsF4TSw","https:\/\/www.youtube.com\/embed\/qrtKLNTB71c","https:\/\/www.youtube.com\/embed\/qrtKLNTB71c","https:\/\/www.youtube.com\/embed\/qrtKLNTB71c","https:\/\/www.youtube.com\/embed\/qrtKLNTB71c"],
episode2: ["https:\/\/www.youtube.com\/embed\/qrtKLNTB71c"],
episode1: ["https:\/\/www.youtube.com\/embed\/qrtKLNTB71c"],
};
What i want to do here is get the first element of array that act as value in a object.
I'm already do something like this
array_eps[Object.keys(array_eps)[0]]
But it's return the whole array not only the first element.
Thankyou
const array_eps = {
episode3: ["https:\/\/www.youtube.com\/embed\/kzZ6KXDM1RI","https:\/\/www.youtube.com\/embed\/T8y_RsF4TSw","https:\/\/www.youtube.com\/embed\/qrtKLNTB71c","https:\/\/www.youtube.com\/embed\/qrtKLNTB71c","https:\/\/www.youtube.com\/embed\/qrtKLNTB71c","https:\/\/www.youtube.com\/embed\/qrtKLNTB71c"],
episode2: ["https:\/\/www.youtube.com\/embed\/qrtKLNTB71c"],
episode1: ["https:\/\/www.youtube.com\/embed\/qrtKLNTB71c"],
};
console.log(array_eps[Object.keys(array_eps)[0]][0]);

Add an object to JSON

I have a settings.json file that contains following data (where 123456789 is a distinct user id):
{
"123456789":
{"button_mode":true}
}
So what I need to do is push a similar id: {button_mode: value} object to this JSON file in case there's no entry for current user's id. I tried to use lcSettings.push() but obviously it did not work since I have an object, not an array. When I put square brackets instead of curly ones to make it an array, my code doesn't do anything at all.
Here's a snippet of it (Node.js):
var lcSettings = JSON.parse(fs.readFileSync('./settings.json', 'utf8'));
var currentUser = id;
if (lcSettings.hasOwnProperty(currentUser)) {
// in case settings.json contains current user's id check for button_mode state
if (lcSettings[currentUser].button_mode == true) {
// if button_mode is on
} else
if (lcSettings[currentUser].button_mode == false) {
// if button_mode is off
}
} else {
// in case there's no entry for current user's id
// here's where I need to push the object for new user.
}
fs.writeFileSync('./settings.json', JSON.stringify(lcSettings))
Does anybody have ideas on how it can be implemented? Any help appreciated.
You can use bracket notation to add a dynamic property to an object:
lcSettings[id] = { button_mode: false };
You may also want to verify that settings.json is not empty otherwise the JSON.parse() will fail. In this case, you would want to initialize lcSettings to an empty object (lcSettings = {}) so the above will work.
To 'push' elements to an object you simply define them, as in
object['123456789'] = { button_mode: true };

Iterate over an array of objects with object having multiple properties

I'm trying to iterate over the following:
state = {
products : [
{
x : "sd",
y : "fdg"
}, {
x : "sdx",
y : "fdgx"
}
]
}
I need to iterate over the above products array and inside object to create:
<tr><td>sd</td><td>fdg</td></tr>
I tried using :
{
this.state.products.map(function(prod) {
return <tr><td>{prod.x}</td><td>{prod.y}</td></tr>;
})
}
but get multiple errors and prod being undefined.
It's possible that logic elsewhere in your component is mutating the state, which in turn may be the root cause of the error thrown during rendering.
Be sure to check that the products array is consistently defined in your components state, and that the items in that array are defined.
One solution here might be to take a more defensive approach to rendering your table row elements, by doing the following:
{
Array.isArray(this.state.products) && this.state.products
.filter(product => !!product)
.map(product => {
return <tr><td>{product.x}</td><td>{product.y}</td></tr>;
})
}
Here, the rendering logic asserts that this.state.products is the expected array type via Array.isArray(). Addtionally, the logic ensures any prop being rendered is defined by first filtering out any undefined prop items via this line:
filter(product => !!product)
Hope that helps!
The problem is that the return statement is an HTML code which is causing the problem whereas you can encode the code into a string and the DOM will treat it as HTML code
this.state.products.map(function(prod){ return "<tr><td>"+prod.x+"</td><td>"+prod.y +"</td> </tr>" }).
you need to add that in one variable return as below:
const prod = this.state.products.map(function(prod) {
return <tr><td>{prod.x}</td><td>{prod.y}</td></tr>;
});
Use the variable inside render lifecycle as below.
{prod}
Here is the working code attached in jsFiddle
Hope this helps!

JavaScript handle JSON array all in [0] after first loop

localContentSet.forEach((child) => {
// console.log("child------->");
// console.log(child);
// console.log("child.contents------->");
// console.log(child[0]);
**let contents = child[0] == null? child.contents: child[0].contents;**
contents.forEach((content) => {
console.log(content);
});
});
hi, all, I have a JSON array has 10 elements in each Object, I found if you were using forEach, all the elements will be put in [0], after the first Object.
the json looks like:
[
{
element1:value,
element2:value,
element3:value,
element4:value,
element5:value,
...
},
{
element1:value,
element2:value,
element3:value,
element4:value,
element5:value,
...
}
...
]
Any idea about how it is please?
with foreach you can not use child[0] try directly child you will get data in child.
if you want that your data must come with array means child[0] than use for loop

Read html's elements attributes like an array?

I'm thinking for develop a web component form, so... I was wondering my self if it's possible read attributes from a html elements. For example:
<my-component input="3" data-input='"name", "address", "email"' textarea="1" data-textarea='"mensaje"'></my-component>
<script>
while i <= elementattributes.length{
elementattributes[i]
}
</script>
I know that I can access through .getAttribute, but this way will take more code... I just want to be something smart :P
Sorry, my english is poor... I hope you can understand what I want to do :P
:)
If you want to get all of the attributes and their values, you can do something like this:
function getElementAttrs(el) {
var attributes = [].slice.call(el.attributes);
return attributes.map(function(attr) {
return {
name: attr.name,
value: attr.value
}
});
}
var allAttrs = getElementAttrs(document.querySelector('my-component'));
console.log(allAttrs);
<my-component input="3" data-input='name,address,email' textarea="1" data-textarea='"mensaje"'></my-component>
The function getElementAttrs returns an array of objects to you with attribute name-value pairs as keys on the object so that you can loop over it, or just pull by key.
You can use dataset to get specific data attribute
var data = document.querySelector('my-component').dataset.input.split(',');
data.forEach(function(e) {
console.log(e)
})
<my-component input="3" data-input='name,address,email' textarea="1" data-textarea='"mensaje"'></my-component>
If you want to return all attributes from element you can use attributes which return array-like object, but you can create object with name-value from that
var data = document.querySelector('my-component').attributes, attr = {};
Array.from(data).forEach(function(e) {
attr[e.name] = e.value;
});
console.log(attr['data-input']);
<my-component input="3" data-input='name,address,email' textarea="1" data-textarea='mensaje'></my-component>
You can just use .attributes:
document.getElementById("ELEMENT_ID").attributes
This will return an object containing each attribute with its associated value. You can then index the attributes array for specific attributes and use .value for it's corresponding value.

Categories

Resources