Javascript: map function appending to an object - javascript

I have a map function which is iterating a response i received from backend. I'm iterating the response as 'tab' like the code below, what i want to do is to insert 'tab.name' as an key inside the object MyObject
my code:
var MyObject = {}
response.data.rows.map(tab => {
MyObject = {
...MyObject,
tab.name
}
})
What i expect is that my object MyObject has every keys and values with the name of tab, e.g:
{
name1: name1,
name2: name2,
name3: name3
}
The problem is that i can not use tab.name inside object

You could use collectjs, goes good..
Anyway if you want to have the keys just do a foreach
let response = [
{name: 'name1', age: '22'},
{name: 'name2', age: '25'},
{name: 'name3', age: '2'},
]
var MyObject = {}
response.forEach(tab => {
MyObject[tab.name] = tab.name
})
console.log(MyObject)

If you really want to use .map(), you could use to create an array of arrays, where each sub-array has a length of 2, and holds the given value at each index.
Then you can use Object.fromEntries() to add the properties from that array structure.
var response = {data:{rows:[{name:"foo"}, {name:"bar"}, {name:"baz"}]}};
var key_val_props = response.data.rows.map(({name}) => [name, name]);
var MyObject = Object.fromEntries(key_val_props);
console.log(MyObject);

Theres no need to copy the object just do
MyObject[tab.name] = tab.name;
I'd also avoid using .map since it will be returning the new reference which I dont think that is what you want.

Related

How do i make every value of objects in a array as String

I have an array of object something like this
[{id:1, name: "alexander"},{id:2, name: "the great"}]
What is the best way to make the value of all keys as string in the array. So the result should be
[{id:"1", name: "alexander"},{id:"1", name: "the great"}]
Note: My Object is very big and is a combination of number and strings or null and also there is no permanent index of the key in the object. The key in the object can come in any order. Though the key will be at the same place for all the objects. So the desired result should have all the value of all objects in the array as a string.
Use Array.map() to iterate the items. In the map's callback, destructure the objects, extract the id use rest syntax to get the other properties of the object. Convert the id to a string via the String() factory, and then rebuild the object using the spread syntax.
Note: If you expect null or undefined ids, you can use the Nullish coalescing operator (??) to get a default value. For example, String(id ?? '').
const arr = [{id:1, name: "alexander"},{id:2, name: "the great"}]
const result = arr.map(({ id, ...rest }) => ({ id: String(id ?? ''), ...rest }))
console.log(result)
You can use the Array forEach method.
users.forEach(user => user.id = user.id.toString())
where users is the array of objects.
You can try it here:
let users = [{id:1, name: "alexander"},{id:2, name: "the great"}];
users.forEach(user => user.id = user.id.toString());
console.log(users)
You can use map function to iterate each object and save it in each array.
var list = [{ id: "1", name: "alexander" }, { id: "1", name: "the great" }]
var namesValues = list.map((item) => {
return item.name;
});
var idValues = list.map((item) => {
return item.id;
});
console.log(namesValues);
console.log(idValues);

Working with list of arrays and accesing its elements in React

I'm using two objects in my app.
First type looks like this:
and I can access the gender like this: data.results[0].gender
So to elaborate on this i decided to record all people in the data array and now i have an object that looks like this:
how do I reference and access names of selected people from an object like this?
Thanks
To be fair, this seems like a poor/messy way to keep data in general, but maybe you could define a map between your people's ids or uuids or usernames, let's say, and the corresponding objects and then call them by their ids to retrieve the info you need on them:
const peopleMap = new Map();
for (person in array){
peopleMap.set(person.id.value, person)
}
ex.
let aparticularid = '92bd-asd1-24nas-213c-3cac-31ac';
let person = peopleMap.get(aparticularid);
let fullname = person.title + ' ' + person.first + ' '+ person.last;
Realistically you'd retrieve the particular id from elsewhere or some event. Or you can map names to the corresponding objects if you can guarantee their uniqueness(if they are not unique, the objects will be overridden in the map)
You can use .map() to iterate over the items of an Array.
Example -
yourArray.map(x => {
const {title, first, last} = x.name;
console.log(`${title} | ${first} } ${last}`)
})
const yourArray = [
{
id: {name: 'HETU', value: 'NAANANFSF'},
name: {title: 'Ms.', first: 'Mila', last: 'Heitet'}
},
{
id: {name: 'Tom', value: 'TANN'},
name: {title: 'Mr.', first: 'Tom', last: 'Altar'}
},
{
id: {name: 'HARRY', value: 'HARSFF'},
name: {title: 'Mr.', first: 'Harry', last: 'Krishna'}
}
];
yourArray.map(x => {
const {title, first, last} = x.name;
console.log(`${title} | ${first} | ${last}`)
})
Based on the second screenshot, this is an array of objects. Lets call the array arr then you can access the name of the i-th person in the following way:
arr[i].name.first and arr[i].name.last respectively.

Select certain values and sort alphabetically in ES6

How can I select on certain values and sort them alphabetically using ES6.
The current codes defines a constant. I wanted to know if I could manipulate this data without having to create a new constant with just the values I need.
export const names = {
John: 'John',
Mike: 'Mike',
David: 'David',
Chris: 'Chris'
};
Return only Chris and David.
Chris
David
const names = {
John: 'John',
Mike: 'Mike',
David: 'David',
Chris: 'Chris',
};
const searchNames = (args, search) => {
const arr = Object.values(args);
const result = arr.filter(n => {
return search.includes(n);
});
return result.sort().join('\n');
};
searchNames(names, ['David', 'Chris']);
// returns: Chris
// David
Not the most elegant, but it works. It would be easier to start with an array instead of an object. It doesn't seem like the object is necessary since the keys and values are identical. Nonetheless, this is a pretty easy task with an array. I converted the obj to an array containing only the values. Then created a new array
filtering out the names we wanted, returned that array sorted alphabetically and in a string format. The ('\n') in the return statement is just delimiting the elements of the array by a new line, since that's the format you showed. But that can be changed to anything, if you don't need the names to be on separate lines.
Just to clarify, as per the documentation, const can be used here:
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.
Yes you can manipulate this data, have a look on how const works in javascrips.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
const names = {
John: 'John',
Mike: 'Mike',
David: 'David',
Chris: 'Chris'
};
console.log(names.John);
names.John = 'noJohn';
console.log(names.John);

Getting multiple values from JSON

I'm attempting to pull multiple values to create a list in the form of a string. When I am pulling my data it responds as such.
data = [{name: 'value'}, {name: 'value'}, {name: 'value'}]
I need the end product to be "value, value, value" although I'm unsure at the moment on how to go about this.
Let's use Array#Map in JavaScript.
You can see how to use it on MDN here
var data = [{name: 'value'}, {name: 'value'}, {name: 'value'}]
var result = data.map(a => a.name);
console.log(result)
const arr = data.map(elem => elem.value)
In your case, the data object is an array.
You can use the map function, that will iterate over the array elements, it returns a new array with values from the map function callback

Pulling the same value out of a series of keys

I'm trying to quickly pull out ‘value’ property from some objects using destructuring.. is there a simple way to get it from this? I think it might be possible with some complicated destructuring thing i haven’t quite grocked.
I know I could use loops and such, but I'd like to make it a bit more elegant. I'm looking for a non-repetitive, ideally 1-2 line solution. I wanted to use a map, but that only works on an array...
formData = {
name: {val: 'myName', key: 'value', etc: 'more data'}
province: {val: 'myProvince', key: 'value', etc: 'more data'}
dateOfBirth: {val: 'myBDAY!', key: 'value', etc: 'more data'}
}
//desired outcome:
{
name: 'myName',
province: 'myProvince',
dateOfBirth: 'myBDAY!'
}
//attempt 1
let customer = { name, province, dateOfBirth} = formData; //hrm doesn't get me there
Destructuring is used to assign multiple variables from different elements of an array or object, that's not what you're doing. You can just do:
let customer = {
name: formData.name.val,
province: formData.province.val,
dateOfBirth: formData.dateOfBirth.val
}
If you don't want to list all the properties explicitly, just use a loop.
let customer = {};
for (var k of Object.keys(formData)) {
customer[k] = formData[k].val;
}
A hard to read one-liner would be:
let customer = Object.keys(formData).reduce(
(acc, key) => Object.assign(acc, {[key]: formData[key].val}), {});
to grab .val off every value in the object, and return a new object with the same keys.
That's basically the equivalent of:
let customers = {};
for (const key of Object.keys(formData)) customers[key] = formData[key].val;
Since you didn't like Barmar's answer, you can use a combination of Object.keys and the resulting array's reduce method:
let customer = Object.keys(formData).reduce(function(acc, key) {
acc[key] = formData[key].val;
return acc;
}, {});
You said you wanted to use destructuring… so let's do that:
let customer = {};
for (let k in formData) ({[k]: {val: customer[k]}} = formData);
But really, avoid that, and use clear and readable property assignment instead :-)

Categories

Resources