How to make Array to Variable - javascript

i have some array looks like this:
const [listArr, setLA]= useState([
{
id: Math.floor(Math.random * 100000),
data: "This is data 1",
},
{
id: Math.floor(Math.random * 100000),
data: "This is data 2",
},
....(and so on)
]);
and i need to extract those data to become 1 variable and get it using console looks like
console.log(data);
//This is data 1\nThis is data2
I've tried using foreach to put 1 by 1 but still didn't work, can you guys help me?

You may use Array#map function to get an array of the values you want and then join them into a string in order to print to the console:
console.log(listArr.map(({ data }) => data).join('\n'))

Related

get the uuid in an object array with Firebase

Hello I would like to know if there would be a method to recover the uuid when I push data in my table I put you in the screenshot below
the code
push(ref(db, `/users/${auth.currentUser.uid}/user/sensors`), {
name: registerInformation.nameBox,
id: registerInformation.idBox,
categories: registerInformation.categories,
routine: registerInformation.routine,
});
The push function returns a Reference object, from which you can get the key with something like this:
const newRef = push(ref(db, `/users/${auth.currentUser.uid}/user/sensors`), {
name: registerInformation.nameBox,
id: registerInformation.idBox,
categories: registerInformation.categories,
routine: registerInformation.routine,
});
console.log(newRef.key);
If you want to use that key in the write operation, you can also separate the creating of the new ID from the writing of the data like this:
const newRef = push(ref(db, `/users/${auth.currentUser.uid}/user/sensors`));
console.log(newRef.key);
set(newRef, {
name: registerInformation.nameBox,
id: registerInformation.idBox,
categories: registerInformation.categories,
routine: registerInformation.routine,
});
In this snippet, the first line is a pure client-side operation that doesn't actually write anything to the database yet.

replace json key with another json value using node js / javascript

testDetails.map(function(data){
let JsonData={
title: data["title"],
url: data["url"],
firstName: data["username"],
work:[{workid:data["workid"].slice(","), workname: "tester"}],
employee: [{employee_id: data["employee_id"].slice(","), employee_desk:"custom"}]
}
})
so my above json output look like this
{
"title":"01"
"url":"employe#url.com",
"firstName":"employee name",
"work":[{"workid":"9371", "workname": "tester"}],
"employee":[{"employee_id":"weh34",employee_desk:"custom"}]
}
and another JSON object where data look like this
let data={
"031w":"ewid3728e",
"9371":"emp_01",
"weh34":"work_place01"
}
The workid and employee id with the JsonData I want to replace with the value which is present inside the data json so my data which is look like this
"work":[{"workid":"9371", "workname": "tester"}],
"employee":[{"employee_id":"weh34",employee_desk:"custom"}]
needed to be look like this
"work":[{"workid":"work_place01", "workname": "tester"}],
"employee":[{"employee_id":"emp_01",employee_desk:"custom"}]
I am trying to replace the code manually like this
work:[{workid:data.weh34, workname: "tester"}],
employee: [{employee_id: data.9371, employee_desk:"custom"}]
but data["workid"].slice(",") and data["employee_id"].slice(",") always get changed so I want to match both the json and fetch the value and place it in my JsonData
Just use the value you got from testDetails as the index in the data object to get the corresponding value.
You need to use a different variable from data as the parameter to the mapping function so you can refer to the external variable data. I changed it to d below.
testDetails.map(d => ({
title: d["title"],
url: d["url"],
firstName: d["username"],
work: [{
workid: data[d["workid"].slice(",")],
workname: "tester"
}],
employee: [{
employee_id: data[d["employee_id"].slice(",")],
employee_desk: "custom"
}]
}));

Two different types of array of objects

I'm trying to sort my array of Star Wars episodes by episode ID. I faced a strange problem. I have first array (marked as "1" on screenshot) and second array (marked as "2" on screenshot).
The first one is just data pasted into code:
const test = [
{ title: 'The Empire Strikes Back', episode_id: 5 },
{ title: 'A New Hope', episode_id: 4 },
{ title: 'Attack of the Clones', episode_id: 2 },
{ title: 'Return of the Jedi', episode_id: 6 },
{ title: 'The Phantom Menace', episode_id: 1 },
{ title: 'Revenge of the Sith', episode_id: 3 },
];
The second one is function which takes an array of endpoints (filmsArray) and then gets the specific title and episode_id from all endpoints, and then pushing it into array as object and returns that array.
const handleGetFilms = (filmsArray) => {
const titlesArray = [];
filmsArray.forEach(async (film) => {
const {
data: { title, episode_id },
} = await axios.get(film);
titlesArray.push({ title, episode_id });
});
return titlesArray;
};
As you can see on the screenshot - sorting for the first array (which is just data pasted into code) works well, but sorting for the second (which is dynamic data) is not working at all. Because of that I have two questions:
Why this sorting isn't working for the second array? (I'm using the same array.sort function for both of these arrays)
Why there's a difference between console.log for those two arrays? Shouldn't they be the same?(Marked as green on the screenshot)
EDIT:
I'm adding the sorting code:
arrayName.sort((a, b) => a.episode_id - b.episode_id)
You must change foreach with normal for loop or other options. forEach loop doesn't support for async await because forEach expects a synchronous function only.

Dynamically Creating object keys

I've been trying to understand and master creating json objects with javascript, however I cannot seem to figure out how to (first iterate something, and use that value as my key). My second problem is when I see my json result, it always seems to be nested with a preceding blank item before it. Here is what I mean:
My current portion of code is:
.then((data)=>{
connection.query("SELECT * FROM amion_onCall", function (err, result, fields){
const fixed = [];
let i;
for (i in result){
aName = result[i].name;
aServ = result[i].specialty;
aShift = result[i].shift;
aOff = result[i].office;
aCell = result[i].cell;
aTag = result[i].tag;
var data = {aServ: {name:aName, service: aServ, shift: aShift, office: aOff, cell: aCell, tag: aTag}};
// console.log(data);
fixed.push(data);
}
fs.writeFile('./data/json/newAmion.json', JSON.stringify(fixed), function(err){
if (err) throw err;
console.log("Wrote New Amion");
});
});
})
The output in my json viewer is:
[
{
"aServ": {
"name": "Dr.John",
"service": "Cardiology",
"shift": "7a-7p",
"office": "123",
"cell": "123-456-789",
"tag": "no tags"
}
},
...and so on for my ~150 entries.
Problem #1: I want to move this up one full level. I'm not sure how to do that, or why it starts so deeply nested.
Problem #2: When I iterate aServ, I want the actual value to be output in the beginning of my json. My current code prints "aServ" statically for everyone...I don't want to do that. For example, this is how I am trying to get my json to output:
{
"Cardiology": {
"name": "Dr.John",
"service": "Cardiology",
"shift": "7a-7p",
"office": "123",
"cell": "123-456-789",
"tag": "no tags"
},
"Pulmonology": { ...and so on
}
Answer 1:
What do you mean by "preceding blank item"? Do you mean "aServe"? If yes, because you did it here var data = {aServ: { ... } }.
Also, you have a lot of items. So those are inside array [].
Answer 2:
// Change it to object instead of array
const fixed = {};
// Inside array
if (!Array.isArray(fixed[aServ])) {
fixed[aServ] = []
}
fixed[aServ].push({
name: aName,
service: aServ,
shift: aShift,
office: aOff,
cell: aCell,
tag: aTag,
})
No need to push item to array.
Remember, if there are multiple aServ with the same value then it will replace the existing item. That is why you should use an array.
Problem #1: I want to move this up one full level. I'm not sure how to do that, or why it starts so deeply nested.
It's nested because you're in an array of objects. Arrays in JavaScript are indicated by the surrounding brackets []. In this case I think it's what you want: you're creating an array of objects.
Problem #2: When I iterate aServ, I want the actual value to be output in the beginning of my json.
This line:
var data = {aServ: {name:aName, service: aServ, shift: aShift, office: aOff, cell: aCell, tag: aTag}}
Needs to be changed to this:
var data = {[aServ]: {name:aName, service: aServ, shift: aShift, office: aOff, cell: aCell, tag: aTag}}
Note the brackets. That will interpolate your variable values as an array key.

lunr.js Add data about an index record

In lunr.js, you can add a unique reference using the .ref() method but I can't find any method to add extra data/info about that particular record. Is it not possible or am I missing something really obvious.
I even tried assigning an object to ref but it saves it as a string.
EDIT
For now I am saving all the contents as a JSON string in .ref(), which works but is really ugly to use.
lunr does not store the documents that you pass it to index at all, the way it indexes means that the original document is not available to lunr at all, so there is no way of passing and storing meta data associated with the indexed object.
A better solution is to keep your records outside of lunr, and use the reference you give to lunr to pull out the record when you get the search results. That way you can store whatever arbitrary meta data you want.
A simple implementation might look like this, its overly simplistic but you get the idea...
var documents = [{
id: 1,
title: "Third rock from the sun",
album: "Are you expirienced",
rating: 8
},{
id: 2,
title: "If 6 Was 9",
album: "Axis bold as love",
rating: 7
},{
id: 3,
title: "1983...(A Merman I Should Turn to Be)",
album: "Electric Ladyland",
rating: 10
}]
var db = documents.reduce(function (acc, document) {
acc[document.id] = document
return acc
}, {})
var idx = lunr(function () {
this.ref('id')
this.field('title', { boost: 10 })
this.field('album')
})
documents.forEach(function (document) {
idx.add(document)
})
var results = idx.search("love").forEach(function (result) {
return db[result.ref]
})

Categories