Creating An Array of Objects From An Object Without Specific Key Values - javascript

Hello this is my first question on this platform so please feel free to remove or edit, or leave criticism.
So I am parsing data from an API in react. The data comes out looking something like this.
data = {
"20": "john",
"20.5": "jim",
"21": "bob",
"21.5": "james",
"22": "carl",
"23": "linda",
"25": "jack",
"25.5": "kyla",
"26": "jenny",
}
And I am trying to dynamically update a webpage using this data. I need to access the ages (keys) and the names (values).
I am putting the object's key value pairs into an array so I can map them inline using array.map(), my code below.
var Array = []
for (const [key, value] of Object.entries(data)) {
Array.push({
age: key,
name: value,
});
}
Now this does for the most part what I am trying to do. The output being a new array.
[
{ age: '20', name: 'john' },
{ age: '21', name: 'bob' },
{ age: '22', name: 'carl' },
{ age: '23', name: 'linda' },
{ age: '25', name: 'jack' },
{ age: '26', name: 'jenny' },
{ age: '20.5', name: 'jim' },
{ age: '21.5', name: 'james' },
{ age: '25.5', name: 'kyla' }
]
Now the problem is that they are not in the same order as they were given. For some reason the .5 ages all sorted at the end of the array. Is this a limitation of array.push()? Am I doing something fundamentally wrong with the Object.entries() function? Or should I simply resort to using sorting methods once the array has been created?

When iterating over objects, ascending whole number keys will always come first. The best approach to this sort of problem would be to change the backend so that it gives you the desired array of objects to begin with, instead of a somewhat broken format that you need to fix later.
If that's not possible, you'll have to fix it client-side by taking all entries, then sorting them.
const input = {
20: 'john',
20.5: 'jim',
21: 'bob',
21.5: 'james',
22: 'carl',
23: 'linda',
25: 'jack',
25.5: 'kyla',
26: 'jenny'
};
const result = Object.entries(input)
.map(([age, name]) => ({ age, name }))
.sort((a, b) => a.age - b.age);
console.log(result);
You may also need to fix the API so that it gives you proper JSON, since
{
20: john
20.5: jim
is not valid syntax.

Related

How to use the method includes() or other methods so that i could filter the array to another that will have only properties that called 'age'

for example I have certain array which has the objects in it:
const people = [
{id: 1, name: 'Michael', age: 26},
{id: 2, name: 'Tom', age: 15},
{id: 3, name: 'Kevin', age: 56},
{id: 4, name: 'Christian', year: 1990},
]
now I need to filter it to the another array which will have the same properties excluding last as i said above, that is, I wanna have objects with property "age" in new array, here is my trying of realize it below:
const ages = array.filter((el, index, arr) => {
if(arr.includes('age')){
return true
}
})
console.log(ages)
Javascript's interpreter returns undefined, what's wrong with my code? thanks to who will solve it
You could run the filter method on the array and inside the filter condition, you could check the object's keys array for the 'age' attribute.
Here's the code for your response.
const ages = array.filter(person => Object.keys(person).includes('age'));
console.log(ages);

Filtering object keys inside an array of objects

Let's assume I'm obtaining an array of objects from a Node Repository, for example:
results = [
{
name: "John",
surname: "Fool",
age: 22
},
{
name: "Erik",
surname: "Owl",
age: 38
}
]
How can I filter every object taking only the keys I need, for example avoiding 'age' key?
filteredResults = [
{
name: "John",
surname: "Fool",
},
{
name: "Erik",
surname: "Owl",
}
]
I've already obtained this by creating another empty array and populating it by looping on the original one, but in case of large-data this would be heavy.
repository.retrieve((error, result) => {
let filteredData = [];
result.forEach(r => {
filteredData.push({
name: r.name,
description: r.description,
});
});
});
In SQL, I would obtain it this way:
SELECT `name, description` FROM results;
You can just rebuild the object as you want
{
name: rec.name,
surname: rec.surname
}
const results = [
{
name: "John",
surname: "Fool",
age: 22
},
{
name: "Erik",
surname: "Owl",
age: 38
}
]
const result = results.map((rec) => {
return {
name: rec.name,
surname: rec.surname
}
})
console.log(result)
Or delete fields that is useless
const results = [
{
name: "John",
surname: "Fool",
age: 22
},
{
name: "Erik",
surname: "Owl",
age: 38
}
]
const result = results.map((rec) => {
delete rec.age
return rec
})
console.log(result)
I suggest you can tell more about what you will need to perform on the output to get the answer that can help.
Case 1. if your original list will survive and you accept your "modified list" to always follow the original list, you may use a generator to wrap your original object, by always not returning those extra properties.
Case 2. if you really want a query system, you may try using real DB thing such as levelDB
Case 3. if you need to display the modified list, write a simple wrapper to fit the format of each list item
Case 4. if you need to snapshot the modified list as object, the method you already made is already a very reasonable method
Case 5. if you need to snapshot the modified list as another output, you can try to directly obtain such output rather than making the intermediate object
You can use map and reduce to simplify this, which obviates the need to create a new array.
var results = [ { name: "John", surname: "Fool", age: 22 }, { name: "Erik", surname: "Owl", age: 38 } ];
let keys = ['name', 'surname'];
var filtered = results.map(obj=>
keys.reduce((acc,curr)=>(acc[curr]=obj[curr],acc), {}));
console.log(filtered);
You can also use object destructuring.
var results = [ { name: "John", surname: "Fool", age: 22 }, { name: "Erik", surname: "Owl", age: 38 } ];
var filtered = results.map(({name,surname})=>({name,surname}));
console.log(filtered);
Take a look at Array.map.It creates the transformed array.
let arr = [
{
name: "John",
surname: "Fool",
age: 22
},
{
name: "Erik",
surname: "Owl",
age: 38
}
]
let result = arr.map((elem) => {
return {
name: elem.name,
surname: elem.surname
}
});
console.log(result);
You can use Array.map() to transform individual elements of the array. And in the callback function use Object destructuring assignment to use only the keys you are interested in and return a new object with only those keys.
let results = [
{ name: "John", surname: "Fool", age: 22 },
{ name: "Erik", surname: "Owl", age: 38 }
];
let modified = results.map(({name, surname}) => ({name, surname}));
console.log(modified);

JavaScript: Comparing two objects

I want to compare two objects to make a new object.
original = [
{id: "A1", name: "Nick", age: 20, country: 'JP', code: 'PHP'}
]
edited = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", name: "Nick", age: 25, country: 'US', code: 'PHP'}
]
Compare two objects ('original' and 'edited')
If 'id' is set, compare the same ids' data, and take the data from 'edited', and get ONLY the 'id' and the data that is edited.
If 'id' is not set keep the whole data
The final object I want is like below;
final = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", age: 25, country: 'US'}
]
I've been trying this using filter, but I can't get desired result...
Try with Array#reduce .
Updated with all key pair match
Validate the edited array id value is available in original array using Array#map and indexOf function
If not push entire object to new array
First recreate the original array to object format like {key:[value]}
Then match each key value pair match or not with forEach inside the reduce function
var original = [{id: "A1", name: "Nick", age: 20, country: 'JP'}];
var edited = [{name: "Mike", age: 30, country: 'US'},{id: "A1", name: "Nick", age: 25, country: 'US'}];
var ids_org = Object.keys(original[0]).reduce((a,b,c)=> (a[b]=original.map(a=> a[b]),a),{});
var res = edited.reduce((a, b) => {
if (b.id) {
Object.keys(b).forEach(i=>{
if(ids_org[i].indexOf(b[i]) > -1 && i != 'id')
delete b[i];
})
a.push(b);
} else {
a.push(b);
}
return a;
}, []);
console.log(res)
use de structuring to extract out id from the object.
use lodash isEqual method to compare and later add back the id to the object.

Comparing collection keys in RxJS?

Wanted to see if RxJS has a quick / elegant way of doing this.
Suppose we have two different array of objects. For example:
A1:
[{ name: 'Sue', age: 25 },
{ name: 'Joe', age: 30 },
{ name: 'Frank', age: 25 },
{ name: 'Sarah', age: 35 }]
A2:
[{ name: 'Sue', age: 25 },
{ name: 'Frank', age: 25 },
{ name: 'Joe', age: 30 },
{ name: 'Sarah', age: 35 }]
The keys we want to compare are identified by the name property.
I was thinking about just producing two arrays of all the names filtering out the duplicates, and then comparing them to make sure they are equal, but thought perhaps RxJS has a slick way of doing this and could also emit an observable of any names that don't have a match?
You can try merging the two lists and then applying the distinct operator with a key selector function (to specify key is "name") so that you get a stream of the de-duped items.
https://rxjs-dev.firebaseapp.com/api/operators/distinct

ES6 Object Spread concat

I am new to object spread. I just knew object spread can be used to concat arrays . In below example i am concatenating variable a and address key. I want to know can we add address key value to each object of a array and get output as Required Output in code.
Can any one help me good reference to learn more on Object Spread.
var a = [{
'name':'jay',
age: 31
},
{
'name':'jay1',
age: 30
},
{
'name':'jay2',
age: 29
}];
var b = {...a, ...{address: 'add'}};
//b output
{name: "jay", age: 31}
{name: "jay1", age: 30}
{name: "jay2", age: 29}
address:"add"
// Required Output
{name: "jay", age: 31, address:"add"}
{name: "jay1", age: 30, address:"add"}
{name: "jay2", age: 29, address:"add"}
{ value:1, ...a, ...b, value:3 }
equals:
Object.assign({value:1}, a, b, {value:3})
In your case you need to do that for every element of your array:
const result = a.map(obj => ({...obj, address:"add"}));

Categories

Resources