display object array as html with out brackets - javascript

Hello i have created an object array in JavaScript. And i'm trying to display the object array as html without the brackets. But i have only started to learn javascript today and i have no idea how i can do it.
let servers = [
{ id: '12345', name: 'server #1', players: 1 },
{ id: '123456', name: 'server #2', players: 2 },
{ id: '1234567', name: 'server #3', players: 3 },
{ id: '1234568', name: 'server #4', players: 4 },
{ id: '1234569', name: 'server #5', players: 5 }
];
document.getElementById("online").innerHTML = JSON.stringify(servers);
<div id="online"></div>
How i'm trying to display it:
id: 12345, name: server #1, players: 1
id: 123456, name: server #2, players: 2
id: 1234567, name: server #3, players: 3
id: 1234568, name: server #4', players: 4
id: 1234569, name: server #5, players: 5
If someone could point me in the right direction i would really appreciate it

How about this approach? 😊
This way you can easily control how the data will be displayed.
let servers = [
{ id: '12345', name: 'server #1', players: 1 },
{ id: '123456', name: 'server #2', players: 2 },
{ id: '1234567', name: 'server #3', players: 3 },
{ id: '1234568', name: 'server #4', players: 4 },
{ id: '1234569', name: 'server #5', players: 5 }
];
var string = "";
servers.map((x) => {
string += `id: ${x.id}, name: ${x.name}, players: ${x.players} <br />`
})
document.getElementById("online").innerHTML = string;
<pre id="online"></pre>

This is easy to use and display,
you can also use map() but you don't need it here. Check difference.
https://stackoverflow.com/a/34426481/10915534
let servers = [
{ id: '12345', name: 'server #1', players: 1 },
{ id: '123456', name: 'server #2', players: 2 },
{ id: '1234567', name: 'server #3', players: 3 },
{ id: '1234568', name: 'server #4', players: 4 },
{ id: '1234569', name: 'server #5', players: 5 }
];
var rows = "";
servers.forEach(function(element,index){
rows += "id: "+element.id + ", name: "+ element.name +", Players: "+element.players+"<br>";
})
document.getElementById("online").innerHTML = rows;
<div id="online"></div>

let servers = [{
id: '12345',
name: 'server #1',
players: 1
},
{
id: '123456',
name: 'server #2',
players: 2
},
{
id: '1234567',
name: 'server #3',
players: 3
},
{
id: '1234568',
name: 'server #4',
players: 4
},
{
id: '1234569',
name: 'server #5',
players: 5
}
];
var getArrData = "";
for (i = 0; i < servers.length; i++) {
getArrData += "id:" + servers[i].id + "name:" + servers[i].name + "players:" + servers[i].players + "<br>";
}
document.getElementById("online").innerHTML = getArrData;
<div id="online"></div>

This is for as many properties in your json.
let servers = [
{ id: '12345', name: 'server #1', players: 1 },
{ id: '123456', name: 'server #2', players: 2 },
{ id: '1234567', name: 'server #3', players: 3 },
{ id: '1234568', name: 'server #4', players: 4 },
{ id: '1234569', name: 'server #5', players: 5 }
];
var output = '';
for(var i = 0; i< servers.length; i++) {;
for(var prop in servers[i]){
output += prop + ': ' + servers[i][prop] + ', ';
}
output += '<br>';
}
document.getElementById("online").innerHTML = output;
<div id="online"></div>

As an alternative to looping through the returned array, if you want to keep your approach using JSON.stringify(), you can do something like this:
const servers = [
{ id: '12345', name: 'server #1', players: 1 },
{ id: '123456', name: 'server #2', players: 2 },
{ id: '1234567', name: 'server #3', players: 3 },
{ id: '1234568', name: 'server #4', players: 4 },
{ id: '1234569', name: 'server #5', players: 5 }
];
function formatJsonString(str) {
const reNewLineInsertPoints = /},/g;
const reDeletions = /{|}|\[|\]|"/g;
const reSpaceInsertPoints = /(:|,)/g;
return str.trim()
.replace(reNewLineInsertPoints, '<br />')
.replace(reDeletions, '')
.replace(reSpaceInsertPoints, '$1 ');
}
document.getElementById("online").innerHTML = formatJsonString(JSON.stringify(servers));
<div id="online"></div>
I created a separate function for readability and re-usability but it is not strictly necessary; you could simply do:
document.getElementById("online").innerHTML = JSON.stringify(servers)
.trim()
.replace(/},/g, '<br />')
.replace(/{|}|\[|\]|"/g, '')
.replace(/(:|,)/g, '$1 ')

Related

New array based on objects inside another array

I have an array of appointments objects:
let appointments = [
{ _id: 54321, name: 'app 1', date: "2022-01-20T09:00:00+01:00"},
{ _id: 66756, name: 'app 2', date: "2022-01-20T08:00:00+01:00"},
{ _id: 76889, name: 'app 3', date: "2022-01-21T08:00:00+01:00"},
{ _id: 35790, name: 'app 4', date: "2022-01-22T08:00:00+01:00"},
{ _id: 35790, name: 'app 5', date: "2022-01-25T09:00:00+01:00"}
]
my goal is to create a new array based on the days of the appointments and place them inside, like so:
{ days:
{ 2022-01-20: [
{ _id: 54321, name: 'app 1', date: "2022-01-20T09:00:00+01:00"},
{ _id: 66756, name: 'app 2', date: "2022-01-20T08:00:00+01:00"}
]},
{ 2022-01-21: [
{ _id: 76889, name: 'app 3', date: "2022-01-21T08:00:00+01:00"}
]},
{ 2022-01-22: [
{ _id: 35790, name: 'app 4', date: "2022-01-22T08:00:00+01:00"}
]},
{ 2022-01-23: []},
{ 2022-01-24: []},
{ 2022-01-25: [
{ _id: 35790, name: 'app 5', date: "2022-01-25T09:00:00+01:00"}
]},
}
The first 10 characters of 'date' could become the new values (excluding duplicates) and inside them there should be the proper appointments, as they are in the source - only organized by the days.
Another feature that I'm trying to make is inserting empty days between the active days (example in the second code)
Thanks for your help
const appointments = [
{ _id: 54321, name: 'app 1', date: "2022-01-20T09:00:00+01:00"},
{ _id: 66756, name: 'app 2', date: "2022-01-20T08:00:00+01:00"},
{ _id: 76889, name: 'app 3', date: "2022-01-21T08:00:00+01:00"},
{ _id: 35790, name: 'app 4', date: "2022-01-22T08:00:00+01:00"},
{ _id: 35790, name: 'app 5', date: "2022-01-25T09:00:00+01:00"}
];
const appointmentsByDate = appointments.reduce(
(acc, appointment) => {
// split the date string and store index 0 as date variable.
const [date] = appointment.date.split('T');
return {
...acc,
// overwrite or add date key to the accumulator.
// if the date key already exists, spread the existing value into the new value
[date]: [...(acc[date] || []), appointment],
};
},
{} // starting accumulator (acc) value
);
console.log(appointmentsByDate);

best way to get unique values of 2 arrays which different structure?

I have 2 arrays like this:
blockedUsers = ['u1', 'u2', 'u3']
videoList = [
{
id: 1,
mp4URL: '...mp4',
user: {
id: 'u1',
name: 'User 1'
}
},
{
id: 2,
mp4URL: '...mp4',
user: {
id: 'u2',
name: 'User 1'
}
},
{
id: 3,
mp4URL: '...mp4',
user: {
id: 'u5',
name: 'User 1'
}
}
]
I want to remove blocked users from video array. At final I will get array has 1 video from u5. How to do that?
Thank you
Filter out elements where user id is not included in blocked users.
videoList.filter(v => !blockedUsers.includes(v.user.id))
There are a lot of methods for the same. Please find Array.filter implementation of the same.
const blockedUsers = ['u1', 'u2', 'u3']
const videoList = [
{ id: 1, mp4URL: '...mp4', user: { id: 'u1', name: 'User 1' } },
{ id: 2, mp4URL: '...mp4', user: { id: 'u2', name: 'User 1' } },
{ id: 3, mp4URL: '...mp4', user: { id: 'u5', name: 'User 1' } }
];
const output = videoList.filter((node) => blockedUsers.indexOf(node.user.id) === -1);
console.log(output);
There are two ways
First way, you could filter the videoList and iterate to check if the user is in the blocked list. We could do this with .includes for blockedUsers, but this way will result in the complexity of O(n*m), given that n is the length of blockedUsers and m is the length of videoList
Second way, you could first turn the blockedUsers into a hash table using Set. This will reduce the query time complexity for blockedUsers from O(n) to O(1). In this way, the overall time complexity would be O(n + m), which is better than the first way
const blockedUsers = ["u1", "u2", "u3"]
const videoList = [ { id: 1, mp4URL: "...mp4", user: { id: "u1", name: "User 1", }, }, { id: 2, mp4URL: "...mp4", user: { id: "u2", name: "User 1", }, }, { id: 3, mp4URL: "...mp4", user: { id: "u5", name: "User 1", }, }, ]
const blockedUsersHashTable = new Set(blockedUsers)
const res = videoList.filter(
({ user: { id } }) => !blockedUsersHashTable.has(id)
)
console.log(res)
If time complexity is not your concern, just go with the first way.
You can filter the list by using the Array.prototype.includes() method.
const
blockedUsers = ['u1', 'u2', 'u3'],
videoList = [
{ id: 1, mp4URL: '...mp4', user: { id: 'u1', name: 'User 1' } },
{ id: 2, mp4URL: '...mp4', user: { id: 'u2', name: 'User 1' } },
{ id: 3, mp4URL: '...mp4', user: { id: 'u5', name: 'User 1' } }
],
allowedVideos = videoList.filter(({ user: { id } }) => !blockedUsers.includes(id));
console.log(allowedVideos);
.as-console-wrapper { top: 0; max-height: 100% !important; }
const blockedUsers = ['u1', 'u2', 'u3'];
const videoList = [
{
id: 1,
mp4URL: '...mp4',
user: {
id: 'u1',
name: 'User 1'
}
},
{
id: 2,
mp4URL: '...mp4',
user: {
id: 'u2',
name: 'User 1'
}
},
{
id: 3,
mp4URL: '...mp4',
user: {
id: 'u5',
name: 'User 1'
}
}
];
const target = videoList.filter(v => !blockedUsers.includes(v.user.id));
console.log(target);

How to match data and combine two arrays of objects? [duplicate]

This question already has answers here:
How can I perform an inner join with two object arrays in JavaScript?
(7 answers)
Closed 1 year ago.
My database gives me the following data:
var responses = [
{ comment: 'Yes', uid: '5hg' },
{ comment: 'Maybe', uid: 'f1' },
{ comment: 'No', uid: 'b1k2' },
{ comment: 'Yes', uid: '6t2' },
{ comment: 'Yes', uid: 'hd1' },
];
var users = [
{ name: 'Trevor Hansen', group: 'Group 1', uid: 'f1' },
{ name: 'Britta Holt', group: 'Group 2', uid: '5hg' },
{ name: 'Jane Smith ', group: 'Group 2', uid: '6t2' },
{ name: 'Sandra Adams', group: 'Group 1', uid: 'c92c' },
{ name: 'Ali Connors', group: 'Group 1', uid: 'b2' },
{ name: 'John Smith', group: 'Group 2', uid: '9l2' },
{ name: 'Sandra Williams', group: 'Group 2', uid: 'hd1' },
{ name: 'Tucker Smith', group: 'Group 1', uid: 'b1k2' },
];
Because I store all of my user data only in users[] for different purposes I need to add some information to responses[] about the user (like their name and group). The uid is unique and can be used to match the data to a user.
Obviously there are less responses than users in responses[]. This should not affect my function and is an expected behavior.
This is the desired output:
var output = [
{ comment: 'Yes', uid: '5hg', name: 'Britta Holt', group: 'Group 2' },
{ comment: 'Maybe', uid: 'f1', name: 'Trevor Hansen', group: 'Group 1' },
{ comment: 'No', uid: 'b1k2', name: 'Tucker Smith', group: 'Group 1' },
{ comment: 'Yes', uid: '6t2', name: 'Jane Smith ', group: 'Group 2' },
{ comment: 'Yes', uid: 'hd1', name: 'Sandra Williams', group: 'Group 2' },
];
How can this be done? Any help is appreciated!
you can try for example:
const output = responses.map(response => {
const user = users.find(u => u.uid === response.uid);
return {...response, ...user}
})
or single liner:
const output = responses.map(response => ({...response, ...users.find(u => u.uid === response.uid)}));

React merge two states in third state

I have three state, two of them have data from different api and the third state need to merge those two states based on IDs. So, the third state should have every data that state1 have and state2 don't have, and every data that state2 have and state1 don't have.
Api1:
data: {
0: {
id: 1234
company: 'String',
name: 'Test'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
}
}
Api2:
data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
lastName: 'Second 2'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1'
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3'
}
}
New Array should be (lastName = name + lastName :
data: {
0: {
id: 1234
company: 'String',
name: 'Test'
lastName: 'Second Test'
}
1: {
id: 2345
company: 'String1',
name: 'Test 1'
lastName: 'Second 2 Test 1'
}
2: {
id: 3456
company: 'String2',
name: 'Test 2'
lastName: 'Second 1 Test 2'
}
3: {
id: 4567
company: 'String3',
name: 'Test 3'
lastName: 'Second 3 Test 3'
}
Fetched Data:
const [state1, setState1] = useState([]);
const [state2, setState2] = useState([]);
const [mergeStates, setMergeStates] = useState([]);
useEffects(() => {
fetch("api1")
.then(data =>{
state1(data);
})
fetch("api2")
.then(data =>{
state2(data);
})
}, []);
useEffects(() => {
// Here I want to merge the responses based on IDs
const lastName = companies.map((response) => ({
name: response.name,
lastName: `${response.name} - ${response.lastName}`
}));
setMergeState(lastName);
}, [state1, state2]);
So, the api2 has lastName that api1 doesn't have. So, the mergedStates need to include that.
based on your quetion to merge the two state, you need to iterate over a state either 1 or 2, while merging them.
useEffects(() => {
const keys = Object.keys(state1);
mergedData = keys.map(key => {
// key will be 0,1,2 as with your quetion
return {
...state1[key],
...state2[key],
fullName: state1[key].name + state2[key].lastName
};
});
}, [state1, state2]);

React Get second object if id is equals with another object id

I'm trying to get second object inside data if this id is equals with the id of another object.
With the code below, I'm able to get only ID and not the whole
data: {
0: {
id: 1234,
name: 'Name 1'
},
2: {
id: 4321,
name: 'Name 2'
},
3: {
id: 876,
name: 'Name 3'
}
}
instanceID: 4321
constructor(props) {
super(props);
this.state = {
defaultInstance: 0
}
}
fetch('api)
.then(response => {
console.log('Data fetched', response);
this.setState({
defaultInstance: [response.data.indexOf(response.data.find((instance) => instance.id === response.instanceID))]
});
});
So, what I want to achieve is to add to the defaultInstance that object
2: {
id: 4321,
name: 'Name 2'
},
Try this :
defaultInstance: response.data.filter(d=> d.id == response.instanceID)
This will help you.
let data = {
0: {
id: 1234,
name: 'Name 1'
},
2: {
id: 4321,
name: 'Name 2'
},
3: {
id: 876,
name: 'Name 3'
}
};
let instanceID = 4321;
let result = Object.values(data).filter(chunk => chunk.id === instanceID);
console.log(result);

Categories