This is probably a simple question, but my lack of JavaScript skills is probably preventing me from figuring out a one-liner to do this. Im using axios to request from an API, im getting a response back (This is for a "Todo" list app), however I need to merge another field into this response.
The snippet of code looks like this:
let mergedIsEditing = {...response.data, isEditing: false}
const lists = [ ...this.state.lists, mergedIsEditing ]
lists is basically what it sounds like (an array of lists), and the response.data is nothing more than an object with a title and description. I thought maybe using Object.assign but since im already spreading out this.state.lists im not sure how that would work. Essentially I just need to add the key/value pair isEditing: false onto that list coming in.
Not to encourage shorter code over readability, but to answer your question, this is how you could do the equivalent to your snippet in 1 line:
let mergedIsEditing = {...response.data, isEditing: false}
const lists = [ ...this.state.lists, mergedIsEditing ]
const lists = [ ...this.state.lists, {...response.data, isEditing: false} ]
Of course, you could prepend this.state.lists =, if that's the desired purpose.
Related
I've already tried to find a solution on stack, but I didn't found a possible reply, so I decided to open a topic to ask:
Let's say we have 2 arrays: one containing "keys" and another one containing "values"
Example:
keys = [CO2, Blood, General, AnotherKey, ... ]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[... [
I have to create a Json with a specific structure like:
[{
name: 'CO2',
data: [2,5,4,6]
}, {
name: 'Blood',
data: [4,5,6]
}, {
name: 'General',
data: [1,3,34.5,43.4]
}, {
...
},
}]
I've tried to make some test bymyself, like concatenate strings and then encode it as json, but I don't think is the correct path to follow and a good implementation of it ... I've also take a look on JSON.PARSE, JSON.stringify, but I never arrived at good solution so... I am asking if someone know the correct way to implements it!
EDIT:
In reality, i didn't find a solution since "name" and "data" are no strings but object
Here's one way to get your desired output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = keys.map((x, i) => {
return {"name": x, "data": values[i]}
})
console.log(output)
However, since you're literally constructing key/value pairs, you should consider whether an object might be a better data format to output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = {}
for (let i=0; i<keys.length; i++) {
output[keys[i]] = values[i]
}
console.log(output)
With this data structure you can easily get the data for any keyword (e.g. output.CO2). With your array structure you would need to iterate over the array every time you wanted to find something in it.
(Note: The reason you weren't getting anywhere useful by searching for JSON methods is that nothing in your question has anything to do with JSON; you're just trying to transform some data from one format to another. JSON is a string representation of a data object.)
So I was stuck on a bug in my React App (I am new to react and JS in general) where I wanted to filter a list of company names so that they are all unique and dont repeat. So having access to github copilot I turned it on and out came a solution that worked but I have no idea why or what its doing. If anyone could help me?
useEffect(() => {
const companyNames = data.map(app => app.companyName);
const uniqueCompanies = [...new Set(companyNames)];
setCompanies(uniqueCompanies);
},[data]);
I dont understand how [...new Set(companyNames)] filters out the unique names or what is happening. To my understanding you can only use the spread operator on an array that already exists so didn't know where the new was coming from either.
The expression const uniqueCompanies = [...new Set(companyNames)]; contains the following interesting properties:
[] is an array literal
new Set(companyNames) a new JavaScript Set that can contain only unique values by design, providing the filtering "out of the box".
... The array spread operator here will spread the Set to Array, thus effectively converting the Set to Array.
So, I have a similar situation as with this question which "SHOULD" work but doesn't
How can I access and process nested objects, arrays or JSON?
My JSON is basically this... reduced for brevity.
NOTE:
"{"message": [{"id":"1","element1":"Something","element1":"Something"},{"id":"2","element1":"Something","element1":"Something"}],"status": "success"}"
What happens is that if I select response coming from the API, I get the entire JSON.
If I type: response.message, I get UNDEFINED. That makes absolutely no sense.
This is what it looks like in sessionStorage:
I just want to do what I've always done: response.message or response.whatever to just give me what's "INSIDE" message and for some reason, no matter what I do, it's not working.
Here's the part of the code where I get the response with message
globalService.commonService('getData', reqPkg).then((response) => {
$scope.theReport.data = JSON.parse(response);
});
if I do this I get undefined
$scope.theReport.data = JSON.parse(response.message);
I've tried JSON.stringify too, same result.
This is from a previous question which works fine and is in deed just the Objects from the Array of Objects.
const arrResult = Object.keys(objCount).map(k => ({'name': k, 'displayName': k, 'count': objCount[k] }));
$scope.theReport.data = JSON.parse(response).message; to get all entries from message into $scope.theReport.data.
Your response is a string, so parse the response and just grab the message key from that.
Hello, I am trying to create an array of the data for height from an api as
[270, 1440, 1440, 1440, 1440] but am having trouble understanding how the process work.
I have tried using
var result = screenshots.map((ele) => ele.height)
, but I know you got to incorporate a key value like
screenshots.map((ele,key) => ele.height)
somehow.
Not exactly sure what your asking, but you can read up on how to use map here.
There is no "key" parameter, only: currentValue, index, and array.
Your example of how to create a "result" array for heights should work.
If you're trying to create an array of objects with a reduced set of keys, you could do something like this:
const result = screenshots.map(ele => ({
height: ele.height,
imageId: ele.image_id
}));
If you provided more clarify with regard to what you're asking, someone might be able to help you better.
I'm a perl programmer learning javascript. In perl, I would frequently use hashes to create 'data structures' from data returned from a database query. For example, I would build hashes like this:
*loop through list of data*
push(#{$hash{$key1}{$key2}}, [$value1, $value2, $value3, $value4]);
*endloop*
this would add a reference to the list of four values to a list in the hash (with multiple keys).
I'm having a hard time finding information on how I would implement a similar structure in javascript. My goal is to read in a JSON file that has a list of objects (which has no particular order) and turn it into a hash so it can be sorted by the keys and then display it in an HTML table.
Perhaps this is the wrong way to think about this problem and javascript will have a different approach. I'd like to know if what I'm trying to do is possible, the code to create the hash, and the code to access the hash.
Thanks,
Rob
This is my straight translation, tested at the Google Chrome console prompt >
> hash = {}
Object {}
> hash["key1"] = {}
Object {}
> hash["key1"]["key2"] = []
[]
> hash["key1"]["key2"].push([ 'value1', 'value2', 'value3', 'value4'])
1
> hash
Object {key1: Object}
> JSON.stringify(hash, null, 2)
"{
"key1": {
"key2": [
[
"value1",
"value2",
"value3",
"value4"
]
]
}
}"
Hash in Perl is just set of key/value pairs. Javascript has similar data structure - Objects. You could do what you want
> a = {}
{}
> a.res = []
[]
> a.res.push([1,2,3])
1
> a.res.push([3,"sd",1])
2
> a
{ res:
[ [ 1, 2, 3 ],
[ 3, 'sd', 1 ] ] }
Javascript does not have an ordered hash and a lookup with multiple keys. You can use the properties of an object to create a lookup by a single unique key and you can then build on that notion as needed. See this answer for an idea how to implement a simple form of hash or set in javascript.
The basic idea is that you create an object and then add key/value pairs to it:
var myLookup = {};
myLookup[key1] = value1;
myLookup[key2] = value2;
Then, you can look up a value by the key:
console.log(myLookup[key1]); // shows value1
If you want more specific help, you will have to be more specific in your question. Show us what the JSON you start with and describe exactly how you want to be able to access it so we can figure out what type of JS data structure makes the most sense to put it in. Remember, once the JSON is parsed, it is already in a javascript data structure at that point so the it becomes a question of what kind of access you need to make to the data to understand whether the data should be restructured with certain key lookups?
It is generally best to concentrate on problem/solution and NOT on trying to do something the same way another language does it.