This question already has answers here:
Converting string array to Name/Value object in javascript
(4 answers)
Closed 4 years ago.
How do I convert a string array:
var names = [
"Bob",
"Michael",
"Lanny"
];
into an object like this?
var names = [
{name:"Bob"},
{name:"Michael"},
{name:"Lanny"}
];
Super simple Array.prototype.map() job
names.map(name => ({ name }))
That is... map each entry (name) to an object with key "name" and value name.
var names = [
"Bob",
"Michael",
"Lanny"
];
console.info(names.map(name => ({ name })))
Silly me, I forgot the most important part
names.map(name => name === 'Bob' ? 'Saab' : name)
.map(name => ({ name }))
Use the Array.map() function to map the array to objects. The map() function will iterate through the array and return a new array holding the result of executing the function on each element in the original array. Eg:
names = names.map(function(ele){return {"name":ele}});
You can do this too:
var names = [
"Bob",
"Michael",
"Lanny"
];
var objNames = []
names.forEach(name => {
objNames.push({
name
})
})
Using ES6 you can set name and it is equal to name: name
you can use the map function.
In general, list.map(f) will produce a new list where each element at position i is the result of applying f to the element at the same position in the original list.
For example:
names.map(function(s) {
return {name: s}
});
Related
This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
How to find object in array by property in javascript?
(3 answers)
Closed 4 months ago.
I have an object called _test shaped in the below form where the first element is id and the second is name:
"_test": [
{id:1, name:andy},{id:2, name:james}, {id:3, name:mike}
]
I then have another field called key. the values that key takes on can equal values of id in the subs
key
I currently use
_test.flatMap( c => c.id).find(elem => elem == key) || null
How can I get this to return the name? I'm at a loss and having a major brain fart.
You can find the name for a given id via:
const
_test = [
{ id: 1, name: 'Andy' },
{ id: 2, name: 'James' },
{ id: 3, name: 'Mike' }
],
key = 2,
{ name } = _test.find(({ id }) => id === key) ?? {};
console.log(name); // James
actually is pretty easy, you just need to use find on your array, it takes a function as an argument.
pd: when doing ([id, name]) I'm destructuring the array, you can change that to:
names.find(entry => key === entry[0])
const names = [
[1, 'andy'],
[2, 'james'],
[3, 'mike']
];
const key = 3;
const solution = names.find(([id, name]) => key === id)
console.log("solution => ", solution)
console.log("just the name => ",
solution[1]);
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);
This question already has answers here:
Converting string array to Name/Value object in javascript
(4 answers)
Closed 4 years ago.
How do I convert a string array:
var names = [
"Bob",
"Michael",
"Lanny"
];
into an object like this?
var names = [
{name:"Bob"},
{name:"Michael"},
{name:"Lanny"}
];
Super simple Array.prototype.map() job
names.map(name => ({ name }))
That is... map each entry (name) to an object with key "name" and value name.
var names = [
"Bob",
"Michael",
"Lanny"
];
console.info(names.map(name => ({ name })))
Silly me, I forgot the most important part
names.map(name => name === 'Bob' ? 'Saab' : name)
.map(name => ({ name }))
Use the Array.map() function to map the array to objects. The map() function will iterate through the array and return a new array holding the result of executing the function on each element in the original array. Eg:
names = names.map(function(ele){return {"name":ele}});
You can do this too:
var names = [
"Bob",
"Michael",
"Lanny"
];
var objNames = []
names.forEach(name => {
objNames.push({
name
})
})
Using ES6 you can set name and it is equal to name: name
you can use the map function.
In general, list.map(f) will produce a new list where each element at position i is the result of applying f to the element at the same position in the original list.
For example:
names.map(function(s) {
return {name: s}
});
I have an object like this:
{
"name":['John','Bob','Ram','Shyam'],
"marks":['64','22','80','32']
}
I have to sort the names. After I sort names, marks must be matched according to the names.
When I use sort() function, It only sorts the names. How can I sort my overall object?
One option is to alter your data structure to be more sortable. For example:
const data = {
names: ['John','Bob','Ram','Shyam'],
marks: ['64','22','80','32']
}
const people = data.names.map((name, i) => ({
name,
mark: data.marks[i]
}))
const sorted = people.sort((a, b) => a.name.localeCompare(b.name))
console.log(sorted)
A second option would be to keep an array of indexes, which you sort based on the data. This doesn't alter your original structures, but I don't think it is a good option, because it would be hard to keep both the names and marks arrays synced. For example:
const data = {
names: ['John','Bob','Ram','Shyam'],
marks: ['64','22','80','32']
}
const index = Array.from(Array(data.names.length).keys())
index.sort((a, b) => data.names[a].localeCompare(data.names[b]))
console.log(index)
// use the names & marks
index.forEach(i => {
console.log(`${data.names[i]} - ${data.marks[i]}`)
})
You can create another key by name rel and its value will be an array of objects , where each object has keys by name name & mark.
While creating this array you can use sort function to sort these objects in order
let obj = {
"name": ['John', 'Bob', 'Ram', 'Shyam'],
"marks": ['64', '22', '80', '32']
}
obj.rel = obj.name.map(function(e, i) {
return {
name: e,
mark: obj.marks[i]
}
}).sort((a, b) => a.name.localeCompare(b.name))
console.log(obj)
This question already has answers here:
Filter array of objects on all properties value
(3 answers)
Closed 5 years ago.
Suppose I have an array like this:
const people = [
{
"name":"pete22",
"age":56
},
{
"name":"sonya56",
"age":22
}
]
I can filter with lodash like this by name:
let result = people.filter(person =>_.includes(person.name,'56')
//{'name':'sonya56'}
What if I want to return all people with '56' in any property? So in the above example it would return both people? I am looking for a compact solution, maybe lodash?
You don't need Lodash to do this as JavaScript natively has support to do these kind of things.
What you need to do is filter the people but also filter each value inside an entry, e.g.:
const people = [{
"name": "pete22",
"age": 56
}, {
"name": "sonya56",
"age": 22
}]
// Filter your 'people' JSON
const filteredPeople = people.filter(person => {
// Filter each 'value' (property) inside each entry in 'people'
return Object.values(person).filter(value => {
// Turn a value into a string and check if it includes the value '56'
return value.toString().includes('56')
})
})
console.log(filteredPeople)
You could just use Array#filter with Object.values, Array#map with strings and check with Array#some and Array#includes.
const
people = [{ name: "pete22", age: 56 }, { name: "sonya56", age: 22 }],
filteredPeople = people.filter(person => Object
.values(person)
.map(String)
.some(v => v.includes('56'))
)
console.log(filteredPeople);
What if I want to return all people with '56' in any property?
You need an array with all such properties with which you want to filter the input array.
var prop = [ "age", "size" ];
Now simply applies the filter in a loop
var valueToMatch = "56";
result = people;
prop.forEach( function( key ){
if ( result.length ) { return true; } //if the result is already empty
result = result.filter( function( peopleObj ){
peopleObj[ key ] == valueToMatch;
});
});
result is the output array filtered with all the properties given in prop array.
Stop using lodash for everything.
JavaScript:
let filtered = people.filter((e) => e.name === ‘foo’ && e.age === 23);
Keep in mind that && forces the two conditions and || says that only one of them must be true.
Extended solution for any number of properties:
var people = [
{ "name":"pete22", "age":56 }, {"name":"sonya56", "age":22 },
{ "name":"john33", "age":33 }, {name: "mike", "login":"56mike", "code": 10 }
],
result = people.filter(function(o){
return Object.keys(o).some(function(k){ return String(o[k]).indexOf("56") !== -1; });
});
console.log(result);
We can filter again with values of Object
people.filter(
hm=>Object.values(hm).filter(
vl=>(vl+'').indexOf(56)>-1).length>0)