This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
Here's my code:
{
"badge_sets":{
"1979-revolution_1":{
"versions":{
"1":{
"image_url":"https://static-cdn.jtvnw.net/badges/v1/7833bb6e-d20d-48ff-a58d-67fe827a4f84/1",
}
}
},
"60-seconds_1":{
"versions":{
"1":{
"image_url":"https://static-cdn.jtvnw.net/badges/v1/1e7252f9-7e80-4d3d-ae42-319f030cca99/1",
}
}
}
}}
Im trying to get something like that using javascript but currently i have no idea how to do it, Can someone help?
1979-revolution_1;https://static-cdn.jtvnw.net/badges/v1/7833bb6e-d20d-48ff-a58d-67fe827a4f84/1
60-seconds_1;https://static-cdn.jtvnw.net/badges/v1/1e7252f9-7e80-4d3d-ae42-319f030cca99/1
You can use ES6's Object.entries() so access the key and value of the nested badge_sets object. Remember that Object.entries() return a [key, value] tuple, so we can use argument destructuring to assign those variables.
The image URL can then be accessed using a combination of dot and bracket notation as such. Then, it is all about using ES6 template literal to put all the parts together to get the format you want.
Object.entries(data.badge_sets).map(([key, value]) => {
return `${key}:${value.versions['1'].image_url}`;
});
Note that this solution will return an array of formatted strings.
You can even take advantage of implicit returns from ES6's arrow function to have a one-liner, at the expense of readability (but looks nice!)
const formattedData = Object.entries(data.badge_sets).map(([key, value]) => `${key}:${value.versions['1'].image_url}`);
See proof-of-concept example:
const data = {
"badge_sets": {
"1979-revolution_1": {
"versions": {
"1": {
"image_url": "https://static-cdn.jtvnw.net/badges/v1/7833bb6e-d20d-48ff-a58d-67fe827a4f84/1",
}
}
},
"60-seconds_1": {
"versions": {
"1": {
"image_url": "https://static-cdn.jtvnw.net/badges/v1/1e7252f9-7e80-4d3d-ae42-319f030cca99/1",
}
}
}
}
};
const formattedData = Object.entries(data.badge_sets).map(([key, value]) => `${key}:${value.versions['1'].image_url}`);
console.log(formattedData);
Related
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 6 months ago.
I am trying to read values from JSON Object using a function that is dynamic.
Sample JSON Object -
var test =
{
"test1": {
"test2": "value2"
},
"test3": {
"test4": {
"test5": "value5"
}
}
}
Now I need to read the test5 value and test2 value so I created the below method and called it twice by passing the argument.
readValue('test1.test2');
readValue('test3.test4.test5');
function readValue(val){
console.log(eval(`test.${val}`));
}
This code is working fine, I am able to get the output.
But is there any alternative to use eval here ??
Better than eval, split your compound key by a dot and iterate it:
let val = (obj, keys) => keys.split('.').reduce(Reflect.get, obj)
var test =
{
"test1": {
"test2": "value2"
},
"test3": {
"test4": {
"test5": "value5"
}
}
}
console.log(val(test, 'test1.test2'))
console.log(val(test, 'test3.test4.test5'))
This question already has answers here:
Convert Array to Object
(46 answers)
Closed 12 months ago.
I need to construct API body for using in javascript fetch. The length of array is twenty or so and I need a loop.
I have an array of objects:
[
{
name:"x",lname:"y"
},
{
name:"x2",lname:"y2"
},
]
and this what I want to achieve:
{
"0":{
"name":"x",
"lname":"y"
},
"1":{
"name":"x2",
"lname":"y2"
},
}
This is raw in postman body:
Any guide and help would be appreciated.
Converting an Array to an Object is easily done with Array.reduce and using the index argument as the key of the properties:
const data = [
{name:"x",lname:"y"},
{name:"x2",lname:"y2"},
]
console.log(
data.reduce((acc, item, i) => ({...acc, [i]:item}) ,{})
)
Or shorter, as suggested by #CherryDT (in the comments below), which automatically converts the Array to an Object consisting of keys derived from the array's items' indices:
const data = [
{name:"x",lname:"y"},
{name:"x2",lname:"y2"},
]
console.log({...data})
Tip: If you want the keys indices to start from 1 and not 0, do:
console.log({...[,...data]})
I am still fairly new to JavaScript and I need help with an issue I am having.
I have a Java function that returns an array of json objects as such:
{
"payload": {
"phone": "1234567890",
"email": "test#test.com",
"contact": {
"personal": "test test",
"professional": "professionaltest test"
}
}
}
Now I have various scenarios in my API test where I am sending a POST request but purposefully missing some of the key/value pairs in the json. Such as:
Send the request by skipping contact.
Send the request by skipping phone.
etc.
I have researched and it seems that using .splice can be used to remove an object. However, from what I understand, the removal criteria is primarily driven by indexes (indices?). I'd rather not use remove by index in case something changes the output of the function in the future. Is there a way to remove by key name? Any alternative methods would be greatly appreciated too.
This is my favorite way to remove an value from an object.
For example, you want to remove phone from the payload object.
var { payload } = // your object
var { phone, ...newValue } = payload
console.log(newValue)
newValue is an copy of payload object without the phone key value.
function removeByKeys(obj, keys) {
return Object.keys(obj).reduce((newObj, key) => {
if (keys.includes(key)) {
return newObj;
}
return { ...newObj, [key]: obj[key] };
}, {});
}
const person = { name: 'bob', age: 36 };
removeByKeys(person, ['age']); // { name: 'bob' }
The has the same API as lodash omit. https://lodash.com/docs/4.17.15#omit. You can use that if you have more complicated use-cases, but the above is simple enough.
This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Convert Javascript array of objects into one object
(4 answers)
How to convert array of objects in one specific object?
(9 answers)
shortest way to create a comma separated object list [duplicate]
(2 answers)
Closed 2 years ago.
I have data that looks like this.
[
{
key: 'myKey'
value: 'myValue'
},
{
key: 'mySecondKey'
value: 'mySecondValue'
},
{
key: 'myThirdKey'
value: 'myThirdValue'
},
]
The amount of objects varies depending on how much values an account has set. I'm trying to return this in a format that looks like this
{
mykey: 'myValue'
mySecondKey: 'mySecondValue'
myThirdkey: 'myThirdValue'
}
Any advice on how I would go about doing this?
You can do something, like
const src = [{key:'myKey',value:'myValue'},{key:'mySecondKey',value:'mySecondValue'},{key:'myThirdKey',value:'myThirdValue'},],
result = Object.assign({}, ...src.map(o => ({[o.key]: o.value})))
console.log(result)
.as-console-wrapper{min-height:100%;}
You can use reduce for this:
const data = [{key:"myKey",value:"myValue"},{key:"mySecondKey",value:"mySecondValue"},{key:"myThirdKey",value:"myThirdValue"}];
const res = data.reduce((obj, {key, value}) => ({...obj, [key]: value}), {});
console.log(res);
Other answers work but I feel like they are a bit complicated, here's a simple for of loop:
const data = [
{
key: 'myKey',
value: 'myValue'
},
{
key: 'mySecondKey',
value: 'mySecondValue'
},
{
key: 'myThirdKey',
value: 'myThirdValue'
}
];
const result = {};
for(const {key, value} of data) {
result[key] = value;
}
console.log(result);
I have an array in JavaScript that I use JSON.stringify() on that ends up looking like this after:
[
{
"typeOfLoan":"Home"
},
{
"typeOfResidency":"Primary"
},
{
"downPayment":"5%"
},
{
"stage":"Just Looking"
},
{
"firstName":"Jared"
},
{
"lastName":"Example"
},
{
"email":"Jared#demo.com"
},
{
"cell":"8888888888"
},
{
"loanofficer":"Jim Loan"
}
]
I want the output to be a standard JSON object so that I can send it in a POST. Before this gets marked as duplicate, I have tried all of the answers I could possibly find already and they all end up not working or having syntax errors that I do not understand how to fix. This array is stored in variable jsonArray.
The array of objects, all with a single key, seems fishy. I suppose you want a single object literal with all the keys, which you can then send to you backend (and parse there). So first, reduce the many objects in a single one, then implement your ajax call to POST it to wherever. Here's how to reduce it:
let arr = [{"typeOfLoan":"Home"},{"typeOfResidency":"Primary"},{"downPayment":"5%"},{"stage":"Just Looking"},{"firstName":"Jared"},{"lastName":"Example"},{"email":"Jared#demo.com"},{"cell":"8888888888"},{"loanofficer":"Jim Loan"}];
let res = arr.reduce((a,b) => {
let key = Object.keys(b)[0];
a[key] = b[key];
return a;
}, {});
console.log(res);
Depending on what you use to send it to the backend, you might need to use JSON.stringify on res
Before stringifying, convert your request payload from an array to an object.
const arr = [{"typeOfLoan":"Home"},{"typeOfResidency":"Primary"},{"downPayment":"5%"},{"stage":"Just Looking"},{"firstName":"Jared"},{"lastName":"Example"},{"email":"Jared#demo.com"},{"cell":"8888888888"},{"loanofficer":"Jim Loan"}];
const payload = arr.reduce(function(acc, prev){
return Object.assign(acc, prev);
}, {});
console.log(payload);