Convert array of objects to another array of objects - javascript

I need to convert array of objects to just objects to use it in table datasource:
{v_report_full: Array(25)}
v_report_full: Array(25)
0:
first_name: "Blake"
last_name: "Thorphan"
middle_name: "Agder"
monh: "2021-02-01 00:00:00"
n_vh: "Delay 00:04:52"
n_vh_s_obeda: "ok"
n_vyh: "ok"
n_vyh_s_obeda: "ok"
name: "oitib"
rtime: null
vh_s_obeda_ts: null
vhod_ts: "2021-02-01 08:59:52"
vyh_s_obeda_ts: null
vyhod_ts: null
__typename: "Ereport"
__proto__: Object
1:.. the same next index
2:.. the same next index
Table datasource requires next order:
const dataSource = [
{
key: '1',
name: 'Mike',
age: 32,
address: '10 Downing Street',
},
{
key: '2',
name: 'John',
age: 42,
address: '10 Downing Street',
},
];
I've tried to use Object.keys, but have not enough expirience to do that. If here is a simple solution, if not I have to write a loop for each row with function to concat, etc?
Upd. These one was I worked with:
let dataSource = (data) ? data.v_report_full.map((value, index, array) => {
return {
id: value.id,
key: value.id,
first_name:(value, 'first_name'),
.....
}
After hatfield advise, I checked once more and it's working! A liitle changes and above code then working now D: What a noob I am.

Related

Parse JSON-like string into object using JavaScript

I have a problem about using JSON-like string parser: sometimes users will not input a correct strict JSON string. For example:
input =
"name: John,
age: 20,
products: [
{ id : 100, name: flower },
{ id : 101, name: snack },
],
home: New York,
education: {
highSchool: {
name: Stuyvesant High School,
GPA: 3.2
},
college: {
name: Fordham University,
GPA: 2.8
}
}"
The input above is not able to parse using JSON.parse() because both key and value does not fit contained by "" (name: John instead of "name": "John")
How can we get the expected output like this:
console.log(customParser(input));
//expected
/*
name: "John",
age: 20,
products: (2) [{...}, {...}]
home: "New York"
education: (2) {highSchool: {...}, college: {...}}
*/
As an alternative to writing your own parser from scratch, you might consider interpreting the user input as YAML. For example, the Node.js command require("js-yaml").load(input) converts your example input into the following Javascript object:
{
name: 'John,',
age: '20,',
products: [ { id: 100, name: 'flower' }, { id: 101, name: 'snack' } ],
home: 'New York,',
education: {
highSchool: { name: 'Stuyvesant High School', GPA: 3.2 },
college: { name: 'Fordham University', GPA: 2.8 }
}
}
Except for the trailing commas at the end of the string-valued properties, that is what you want. Either educate your users to leave these commas out, or write a pre-processor that removes them before calling the .load function of js-yaml.

DynamoDB, BatchWriteItem for an array - AWS V3

I have an array I am using to create a put for batchwriteitem.
const people = [{
location: 'London',
name: 'Tony Wilson',
pets: [ {name: 'Cuddles', age: 4}, { name: 'Jess', age: 2}]
},
{
location: 'Manchester',
name: 'Liz Smith',
pets: [ {name: 'Fluffy', age: 4}, { name: 'Keith the cat', age: 2}]
}
]
My batchwriteitem loop is working for individual items
location: { S : item.location },
but when I try and input the pets array as an array it fails
pets: { M: item.pets },
So this all works except the pets array.
const request = pets.map(item => {
const createdDate = Date.now();
return {
PutRequest: {
Item: {
location: { S : item.location },
createdDate:{ N: createdDate },
pets: { M: item.pets }
}
}
});
Do I need to break down the pets array into types and if so how can I achieve this?
Edit
pets: { L: item.pets }, does not work
**Cannot read properties of undefined (reading '0')
and the old syntax without the types does not work on v3 with the document client for me.
Pets is an array, which is also known as a list type. You are setting it as a dictionary/map type as you've set the value to M. It should be L:
pets: { L: item.pets },
I would advise that you use the Document Client as it means you do not need to think about the type conversions, and just use native JSON objects:
pets: item.pets,

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

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.

search a string from an array whose keys and values are dynamic

I have the following array :
var Array = [{id:100,name:'N1',state:'delhi',country:'india',status:'active'},
{id:101,name:'N2',state:'kenya',country:'africa',status:'suspended'}
{id:102,name:'N3',state:'kerala',country:'india',status:'inactive'}
{id:103,name:'N4',state:'victoria',country:'australia',status:'active'}]
and I have a search field , where I need to filter the array with that searched value and return the matched object. The problem here for me is I donot know what key and value pairs may come in the above array , Key value pairs are generated dynamically ,also how can I search the array using Regex . It should match with each char I type and return the matching object in an array ? the result should look something like this :
search key : ind
[{id:100,name:'N1',state:'delhi',country:'india',status:'active'},
{id:102,name:'N3',state:'kerala',country:'india',status:'inactive'}]
search key : N2
[{id:101,name:'N2',state:'kenya',country:'africa',status:'suspended'}]
Any suggestions would be appreciated. Thanks
You could filter the array and check the value by a direct check, if you need to seach for parts of strings or for case independent values.
function search(value) {
return array.filter(o => Object.values(o).some(v => v === value));
}
var array = [{ id: 100, name: 'N1', state: 'delhi', country: 'india', status: 'active' }, { id: 101, name: 'N2', state: 'kenya', country: 'africa', status: 'suspended' }, { id: 102, name: 'N3', state: 'kerala', country: 'india', status: 'inactive' }, { id: 103, name: 'N4', state: 'victoria', country: 'australia', status: 'active' }];
console.log(search('india'));
console.log(search('N2'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Extend observableArray with data from a second source

i create an observableArray from an Ajax Source which is working pretty well. Now I want to extend some of the array items with data from a second source.
For example:
{ id: 1, name: 'Hugo', age: 18 }
... later I want to add:
{ id: 1, city: 'New York', country: 'US' }
... which should result in:
{ id: 1, name: 'Hugo', age: 18, city: 'New York', country: 'US' }
Is this possible with the ko.mapping plugin? I already did some tests with the result that the mapped properties of the items in the array have been replaced by properties from the second source.
Solution
Well, it was actually pretty easy to solve. When adding the new data with the mapping plugin I just have to check for the key. The existing data is just extended with the additional data.
ko.mapping.fromJS(modifications, {
key: function(data) {
return ko.unwrap(data.id);
}
}, originalData);
If the properties aren't observables you can use ko.utils.extend.
var original = { id: 1, name: 'Hugo', age: 18 };
var modifications ={ id: 1, city: 'New York', country: 'US' };
var result2 = ko.utils.extend(original, modifications);
console.log(JSON.stringify(result2));
See fiddle

Categories

Resources