Cannot trim object properties using Javascript or JQuery - javascript

I have not been able to find a way to trim (get rid of the white space at the beginning and end of each string) the properties of the array of objects in my code. Following the advice in other threads on here did not work.
I have an array of objects named 'res'. The properties below are in 'res.d'. How can I trim this object and then JSON.parse it as such:
res.d = JSON.parse(res.d)
Thanks
[{"id":"FARM, LODGE","name":"104"},
{"id":"Barn
","name":"124069"},{"id":"Lg\u0027s Barn Fm
","name":"124820"},{"id":"Ld\u0027s Hill Fm
","name":"125103"},{"id
":"Lord\u0027s Wood Fm
","name":"125126"},{"id":"Lo\u0027s Court Fm
","name":"125345"},{"id":"Lo\u0027s Copse ","name":"162"},
{"id"
:"Lodge "}]

You could do something like this:
const items = [
{ id: " LODGE FARM WEST TO LOWER LODGE FARM, LOWER LODGE", name: "10444" },
{ id: "Hello world ", name: "5555" }
];
const res = items.map(item => {
return {
id: item.id.trim(),
name: item.name.trim()
};
});

let newObj = res.d.map((value) => {
return{
id: value.id.trim(),
name: value.name.trim()
}
})
console.log(newObj)
This should trim the values in your object and 'newObj' will have new values

You could also use lodash after requiring it in your code.
If res.d is an array of objects
_.map(res.d, val => _.mapValues(val, _.trim()));
Otherwise if res.d is an object
_.mapValues(res.d, _.trim);
Ref: https://lodash.com/docs/#trim

Related

How to convert a 2D Javascript array to object with identifiers

What's the best way to convert a 2D array into an object with identifiers that count up?
There could be an unlimited number of identifiers in the object - based on what's in the array.
So in the array we might have
data: [
["Lisa", "Heinz"],
["Bob", "Sleigh"]
]
And we'd be keen that the array looked something like this in the end:
data: {
person1 {
{name: Lisa},
{last_name: Heinz}
},
person2 {
{name: Bob},
{last_name: Sleigh}
}
}
Using map I can create an array of objects, but this isn't quite
json = formData.map(function(x) {
return {
"name": x[0],
"last_name": x[1]
}
})
console.log(json);
Something like this? I changed your object structure a bit to be easier to access.
let newDataObj = {}
for (let person of data) {
const identifier = `person${data.indexOf(person)}`;
const [name, last_name] = person;
newDataObj[identifier] = { name, last_name };
}

Group values keys based for each other value key

Sorry for bad title, I don't really know how to phrase this and this might be trivial problem ...
The data that comes from the array looks like this, each name can have an indefinite amount of sequence, what I want to do is group them by name and put each sequence in an array
[
{
name: 'Mike',
sequence: 'AAAA',
},
{
name: 'Bob',
sequence: 'ABAB',
},
{
name: 'Bob',
sequence: 'AAAB',
},
{
name: 'Marvin',
sequence: 'AAAA',
},
{
name: 'Marvin',
sequence: 'AABA',
},
{
name: 'Marvin',
sequence: 'BBBB',
},
]
What I am looking to return for each name by using console.log(name, array) for example would be something like this
Mike ["AAAA"]
Bob ["ABAB","AAAB"]
Marvin ["AAAA","AABA","BBBB"]
Thank you very much!
As mentioned in the comments, it seems you have tried some ways to solve the problem.
You can try following solution
Use Array.reduce to convert your array into an object with keys as name and value as array of sequences
In the reduce function, check whether the name exist in the resultant object. If it exists, concat the sequence to it (using spread syntax) else add a new entry with an array with sequence.
let input = [{name:'Mike',sequence:'AAAA',},{name:'Bob',sequence:'ABAB',},{name:'Bob',sequence:'AAAB',},{name:'Marvin',sequence:'AAAA',},{name:'Marvin',sequence:'AABA',},{name:'Marvin',sequence:'BBBB',}];
let result = input.reduce((a, {name, sequence}) => Object.assign(a, {[name] : a[name] ? [...a[name], sequence]: [sequence]}), {});
console.log(result);
inputArray.reduce((acc,{name,sequence}) => {
let obj = acc.find(a => a.name === name);
obj ? obj.sequence.push(sequence)
: acc.push({name,sequence:[sequence]});
return acc;
}, [])

Match array value with value in an array of objects javascript

I am trying to work out how I can return a list with values from the own key in the array bellow if the object name value matches values in the lookupvalues array
lookupvalues = ["ross","linda"]
resources = [{own: "car", name: "bob"},{own: "bike", name: "ross"},{own: "plane", name: "linda"}]
wanted_output = ["bike","plane"]
I am struggling a bit with a good method to use for when I need to compare value in an object with array values. Is there a reasonable straight forward way to do this?
I must say how impressed I am that I got 4 replies with working examples at the same time!
One way (array method chaining) is that you could filter by name and map to grap each's own
const lookupvalues = ["ross", "linda"]
const resources = [
{ own: "car", name: "bob" },
{ own: "bike", name: "ross" },
{ own: "plane", name: "linda" },
]
const res = resources
.filter(({ name }) => lookupvalues.includes(name))
.map(({ own }) => own)
console.log(res)
resources.filter(resource => lookupvalues.includes(resource.name))
.map(resource => resource.own);
This will filter by the items that have names that are included in lookupvalues, and then transform the array into an array of the own values of those remaining.
You can take the help of Array#filter and Array#map:
const lookupvalues = ["ross","linda"]
const resources = [{own: "car", name: "bob"},{own: "bike", name: "ross"},{own: "plane", name: "linda"}]
const filterRes = (arr) => {
const lookup = new Set(lookupvalues);
return arr.filter(({name}) => lookup.has(name))
.map(({own}) => own);
}
console.log(filterRes(resources));
resources.filter(item => lookupvalues.indexOf(item.name) > -1).map(item => item.own)

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);

map over properties in array and concat a string in JavaScript es6

I have the following array of objects for example some authors and I want to map through them and return a string which has been concatenated with some formatting. I am for some reason having an issue with this fairly easy thing.
const authors = [ { id: 1, name: 'Steven'}, {id: 2, name: 'Nick'}]
let names = authors.map( (a, i) => {
return `${a.name} is cool`
})
console.log(names)
// ["Steven is cool","Nick is cool"]
// but I really want the string "Steven is cool Nick is cool"
How can I instead get this to map through and format it to a string?
e.g. "Steven is cool Nick is cool"
Use Array#Join :
authors.map((a) => `${a.name} is cool`).join(' ');
DEMO
NOTE : join is not related to ES6 , it is old .
i for one prefer the use of reduce
ES5 version
autors.reduce(function (str, person) {
return (str+' '+person.name+ ' is cool');
}, '');
ES6 version
autors.reduce((str, person) => `${str} ${person.name} is cool`, '');
Here is another version so you don't have to map --> join.. you can just reduce.
const authors = [ { id: 1, name: 'Steven'}, {id: 2, name: 'Nick'}]
console.log(authors.reduce( (p,c) => `${p} ${c.name} is cool `, ""))

Categories

Resources