Print with key and value from array of objects - javascript

I have an array of objects. I want to get the key and value and print the data. eg. I have id, username and password and I want the username and password.
[
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
]
The output should be
name : admin
password : admin,
name : user
password : user,
name : superadmin
password : superadmin

To iterate key values dynamically, you have to iterate object.
let arr = [
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
];
arr.forEach((item, i) => {
for(let key in item) {
console.log(`${key}: ${item[key]}`);
}
});
If you would like to display only name and password, then you can add a condition.
arr.forEach((item, i) => {
for(let key in item) {
if (key === 'name' || key === "password") {
console.log(`${key}: ${item[key]}`);
}
}
});

Given the array you have, you simply need to loop through it:
var arr = [
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
]
arr.forEach(function(obj) {
console.log('name: ' + obj.name);
console.log('password: ' + obj.password);
})

let data = [
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
];
var out_data = data.reduce((a, b) => a + 'name: ' + b.name + ', password: ' + b.password + ' ', '');
console.log(out_data);

var arr = [
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
]
[![enter image description here][1]][1]
Loop through the array
arr.forEach(function(data) {
console.log('name', data.name);
console.log('password', data.password);
})
[1]: https://i.stack.imgur.com/uYA9i.png

Related

reduce() object by arraykey is not using the first key javascript

const cliente = {
nome: "Andre",
idade: 36,
cpf: "123.456.789.10",
email: "andre#gmail.com"
}
const chaves = ["nome", "idade", "cpf", "email"];
const clienteString = chaves.reduce((acum, curr) => acum += curr + ":" + cliente[curr] + ";")
console.log(clienteString);
the current output is: **nome**idade:36;cpf:123.456.789.10;email:andre#gmail.com;
the value of the key "nome:" is not being considered in the string
it should output this: nome:Andre;idade:36;cpf:123.456.789-10;email:andre#gmail.com;
what am i doing wrong?
This is a simpler version that does what you want:
const cliente = {
nome: "Andre",
idade: 36,
cpf: "123.456.789.10",
email: "andre#gmail.com",
};
console.log(
Object.entries(cliente)
.map(([key, value]) => `${key}:${value};`)
.join("")
);
Object.entries returns an array of ["key", "value"]. Then we map over that and turn it into an array of "key:value;". Then we join the array of "key:value;" into a string.

How to format filtered strings and return formated values? Vanilla JS loop

I have array:
link https://api/v1/3
link https://api/v1/3/user-data
link https://api/v1/3/customer-data
link https://api/v1/3/suppliers-sup
i am filter array :
let res = val.match(/.*\/(.*)/)[1];
second way to filter :
const result = links.reduce((acc, {href: link}) => {
const last = link.split('/').pop();
if (!(last == Number(last))) acc.push(last);
return acc;
}, []);
And right now results is:
[
"user-data",
"customer-data",
"suppliers-sup"
]
first logic way is with "3" item but no important for now.
What i need ?
to filter to results be:
[
"User data",
"Customer data",
"Suppliers sup"
]
With first letter big and to remove "-" and apply space
You can format the data like this:
// Sample Data
const data = [
"user-data",
"customer-data",
"suppliers-sup"
]
const formattedData = data.map(item => {
// Seperate words into an array
let dataItems = item.split("-")
// Capitalize first letter of each word
dataItems = dataItems.map(word => word.charAt(0).toUpperCase() + word.slice(1))
// Join the words back together
return dataItems.join(" ")
})
In a concise manner, you can achieve your result as -
console.log(
[
"https://api/v1/3",
"https://api/v1/3/user-data",
"https://api/v1/3/customer-data",
"https://api/v1/3/suppliers-sup"
].reduce((acc, href) => {
let result = href.replace(/.*\/([a-z])?(.*)/,
(_, $1, $2) => $1 ? $1.toUpperCase() + $2 : "")
if (result) return [...acc, result]
return acc
}, [])
)

Trying to transform this string to an object

I have this string:
posts{id,title},posts2{id,title}
I'd like to transform it to an object:
{
posts: [
'id',
'title'
],
posts2: [
'id',
'title'
]
}
How can I do this?
Given that the string will be valid with the specified format:
You can split the string into pairs of key - list items.
Then, iterate over them and insert each into an object as follows:
const stringify = string => {
const obj = {};
if(string) {
const pairs = string.substring(0,string.length-1).split('},');
pairs.forEach(pair => {
const [key,value] = pair.split('{');
obj[key] = value.split(",").filter(String);
});
}
return obj;
}
console.log( stringify('posts{id,title},posts2{id,title}') );
console.log( stringify('posts{id,title}') );
console.log( stringify('posts{}') );
console.log( stringify('') );
This snippet works until you work with a 1-level object. If you need to parse nested object, you've to slightly refactor it.
const input = 'posts{id,title},posts2{id,title}';
const parse = (input) => {
return input
.replaceAll('{', '[')
.replaceAll('}', ']')
.replaceAll('],', '] , ')
.split(' , ')
.reduce((_, item) => {
const key = item.split('[')[0];
const value = item
.replace(`${key}[`, '')
.replace(']', '')
.split(',')
return {
..._,
[key]: value
};
}, {})
};
const parsed = parse(input);
Anyway I don't know what's the benefit of dealing with this notation.

Push value to object if key already exists during Array.map

I have an array that looks like this:
let movies = [
'terminator.1',
'terminator.2',
'terminator.3',
'harry-potter.1',
'harry-potter.3',
'harry-potter.2',
'star-wars.1'
]
and I would like to have an object like this:
{
"terminator": [1,2,3],
"harry-potter": [1,2,3],
"star-wars": [1]
}
so far I'm able to have an object like this
{
{ terminator: [ '1' ] },
{ terminator: [ '2' ] },
{ terminator: [ '3' ] },
{ 'harry-potter': [ '1' ] },
{ 'harry-potter': [ '3' ] },
{ 'harry-potter': [ '2' ] },
{ 'star-wars': [ '1' ] }
}
I would like to know if there is a way to check during an Array.map when I'm generating my object if there is already a certain key and if there is to push the value to the corresponding array instead of creating a new key-value pair.
This is the code that I currently use for my solution. Thanks in advance.
let movies = [
'terminator.1',
'terminator.2',
'terminator.3',
'harry-potter.1',
'harry-potter.3',
'harry-potter.2',
'star-wars.1'
]
let t = movies.map(m => {
let [name, number] = [m.split('.')[0],m.split('.')[1]]
return {[name]: [number]}
})
console.log(t)
You can do this with a single Array.reduce and one array destructuring in order to get the key/value combination:
let movies = [ 'terminator.1', 'terminator.2', 'terminator.3', 'harry-potter.1', 'harry-potter.3', 'harry-potter.2', 'star-wars.1' ]
const result = movies.reduce((r,c) => {
let [k,v] = c.split('.')
r[k] = [...r[k] || [], +v]
return r
},{})
console.log(result)
const movies = ['terminator.1', 'terminator.2', 'terminator.3', 'harry-potter.1', 'harry-potter.3', 'harry-potter.2', 'star-wars.1']
const moviesMap = {}
movies.forEach(data => {
const [title, id] = data.split('.')
if (moviesMap[title]) {
moviesMap[title].push(id)
} else {
moviesMap[title] = [id]
}
})
console.log(moviesMap)
That's a job for Array#reduce, not Array#map:
let t = movies.reduce((acc, movie) => { // for each movie in movies
let [name, number] = movie.split('.'); // split the movie by "." and store the first part in name and the second in number
if(acc[name]) { // if the accumulator already has an entry for this movie name
acc[name].push(number); // then push this movie number into that entry's array
} else { // otherwise
acc[name] = [number]; // create an entry for this movie name that initially contains this movie number
}
return acc;
}, Object.create(null)); // Object.create(null) is better than just {} as it creates a prototypeless object which means we can do if(acc[name]) safely
Note: If you want to coerce the numbers into actual numbers and not keep them as strings, then use the unary + to implicitly convert them: +number.
Example:
let movies = [ 'terminator.1', 'terminator.2', 'terminator.3', 'harry-potter.1', 'harry-potter.3', 'harry-potter.2', 'star-wars.1' ];
let t = movies.reduce((acc, movie) => {
let [name, number] = movie.split(".");
if(acc[name]) {
acc[name].push(number);
} else {
acc[name] = [number];
}
return acc;
}, Object.create(null));
console.log(t);

Lodash: Join values by given key

I am trying to search easy function on Lodash.js for joining values by given key or something...
Example:
const obj = {firstname : 'John', title: 'Mr.', lastname: 'Due'}
Expected results:
Mr. John Due
Any function like _.join() but better and I can do something like..
_.joinX(obj, ['title', 'firstname', 'lastname'], ' ')
Why not just...?
obj.title + ' ' + obj.firstname + ' ' + obj.lastname
Because sometimes my object is so long like... (And I will not give more variable)
obj.current.user.info.title + ' ' + obj.current.user.info.firstname + ' ' + obj.current.user.info.lastname
You can port the following to Lodash.
const joinByKeys = (obj = {}, props = [], separator = '') => {
// empty array.
let arr = [];
// push props to array
props.forEach(p => arr.push(obj[p]))
// return the joined array.
return arr.join(separator);
}
const obj = {firstname : 'John', title: 'Mr.', lastname: 'Due'}
console.log( joinByKeys(obj, ['title', 'firstname', 'lastname'], ' ') );
I think I got it:
const obj = {firstname : 'John', title: 'Mr.', lastname: 'Due'}
let name = _(obj).pick(['title', 'firstname', 'lastname']).values().join(' ')
console.log(name)
Not really special function as I expected but have to run tho Lodash's functions a bit

Categories

Resources