How to create dynamic table headers from JSON in React? - javascript

I have a JSON array of objects, I want to create a dynamic table columns/headers based on it in React.
The data:
example = [
{
id: 0,
city: 'New York',
},
{
id: 1,
city: 'Paris',
},
]
I want to iterate through the array, get the key and add extra fields.
So far I have:
columns() {
return Object.keys(Example[0]).map((key) => {
return {
cityName: key,
capital: false,
};
});
}
I get the keys, but they are unordered (random) and the extra field is added to all the objects. I want to get each key to use it as table header (column name) and be able to change capital for each object.
How can I do that in React?

You can use Array.map for this.
example = [
{
id: 0,
city: 'New York',
},
{
id: 1,
city: 'Paris',
},
];
example.map((obj) => {
return {
CITY : obj.city,
ID : obj.id
// Do whatever with the objects
}
})

arr => arr && arr[0] ? object.keys(arr[0]) : [];
make sure all items in array have same keys

Related

How can I extract and pair the values of an array based object

I'm trying to create a String based upon an object consisting of several key-value pairs.
Example:
[{ name: 'cookie1', value: 'false' },
{ name: 'cookie2', value: '123' },
{ name: 'cookie3',value: 'abc'}]
What I'm trying to achieve (string):
cookie1: false, cookie2: 123, cookie3: abc
I've tried to extract just the val using map like this (played around moving around values):
var output = cookies.map(d => {
return {
"name": d.name,
"value": d.value,
}
})
One way to do this is to map the array of objects into name: value strings and then join them with , :
const data = [{ name: 'cookie1', value: 'false' },
{ name: 'cookie2', value: '123' },
{ name: 'cookie3',value: 'abc'}]
const result = data.map(({ name, value }) => `${name}: ${value}`).join(', ')
console.log(result)

Destructuring data in state from external file in React

I want to receive all city name's from an external .js file to compare them later with the input value. The problem is when I destructure like const { city } = this.state.cities; and console.log, it return undefined.
const cities = [
{
key: 1,
city: "Cambridge"
},
{
key: 2,
city: "Durango"
},
{
key: 3,
city: "Atlanta"
},
{
key: 4,
city: "Sacramento"
},
{
key: 2,
city: "San Francisco"
}
];
export default cities;
and JSX file
class Filters extends React.Component {
state = {
cities: cities,
categories: categories,
types: types,
salaries: salary
};
How do I can get to cities without setting a specific index of object?
If you don't want to get an object by array index, you can get it by key or city like:
cities.find(e => e.key === 1)
or
cities.find(e => e.city === 'city')

how to search nested objects and group according to a field

I have an array that contains nested objects, and i want to filter the objects according to a particular field. Items array contains an item object, that contains some particular field like name, id, price, and vendorid. I want to sort and filter the array according to the vendorid field. For example an array like :
var items=[{item:{name:"cap",
id:"5d767e1358ad1d0ca4894592",
price:50,
vendorid:"5d72d2a6d87c4628ba60e046"
},
}
{item:{name:"shorts",
price:100,
vendorid:"5d71c51f2092d318a1bf8f53"
}
},
{item:{name:"shoes",
price:90,
vendorid:"5d71c51f2092d318a1bf8f53"
}
}
{item:{name:"black hood",
price:120,
vendorid:"5d71c51f2092d318a1bf8f53"
}
}
]
I want to create an object that outputs this :
results = {"5d71c51f2092d318a1bf8f53":[{name:"shorts"
price:100,
vendorid:"5d71c51f2092d318a1bf8f53"},
{name:"shoes",
price:90,
vendorid:"5d71c51f2092d318a1bf8f53"},
{name:"black hood",
price:120,
vendorid:"5d71c51f2092d318a1bf8f53"}
],
"5d72d2a6d87c4628ba60e046":[{name:"cap",
id:"5d767e1358ad1d0ca4894592",
price:50,
vendorid:"5d72d2a6d87c4628ba60e046"
}
]
}
The results object format is {vendorid:[array containing objects with the same vendorid]}.
Thanks very much!!!
You can use reduce() method to do that.
var items = [{ item: { name: "cap", id: "5d767e1358ad1d0ca4894592", price: 50, vendorid: "5d72d2a6d87c4628ba60e046" } } ,{ item: { name: "shorts", price: 100, vendorid: "5d71c51f2092d318a1bf8f53" } }, { item: { name: "shoes", price: 90, vendorid: "5d71c51f2092d318a1bf8f53" } }, { item: { name: "black hood", price: 120, vendorid: "5d71c51f2092d318a1bf8f53" } } ];
let result = items.reduce((obj, currentValue) => {
if (!obj[currentValue.item.vendorid]) {
obj[currentValue.item.vendorid] = [];
}
obj[currentValue.item.vendorid].push({
...currentValue.item
});
return obj;
}, {});
const orderedResult = {};
// Sorting on vendorid.
Object.keys(result).sort().forEach(key => orderedResult[key] = result[key]);
console.log(orderedResult);
A note on ordering of object properties:
As of ECMAScript 2015 (ES6), object's own properties do have order
for some operations, but relying on it isn't a good idea. If order is
important, then better to use an array or something similar.

how to loop through multiple arrays inside an array and filter a value from it-Javascript

I'm using EXTJS framework for my code.
below is my array structure:
data = [{
id: 22,
rows: [{
id: "673627",
name: "ABS",
address: "536street"
}, {
id: "333",
name: "TEST$$",
address: "536street"
}, {
id: "999",
name: "TEST$$",
address: "536street"
}]
}, {
id: 33,
rows: [{
id: "899",
name: "TES",
address: "536street"
}, {
id: "333",
name: "TEST$$",
address: "536street"
}, {
id: "999",
name: "TES673",
address: "536street"
}]
}]
Now I want to filter the name from this array, whose value I'm comparing with say "TEST$$".
I'm doing this;
Ext.each(data, function(item) {
filter = item.rows.filter(function(name) {
return name.name === "TEST$$";
}, this);
}, this);
console.log(filter);
In this case, it returns only 1 match, where as I have 3 matches for this particular value. It returns the match from the last item in the data array and hence I dont get all the matching values, any idea how this can be looped to get all values matching?
thx!
You're reassigning the filter variable on every iteration over the data array:
filter = item.rows.filter(function(name) {
return name.name === "TEST$$";
}, this);
On the last iteration, there is only one match, the one with id of 333, so that's the only one that you see after running the Ext.each. Try pushing to an external array that doesn't get overwritten instead:
const testItems = [];
Ext.each(data, function(item) {
const filtered = item.rows.filter(row => row.name === "TEST$$")
testItems.push(...filtered);
});
console.log(testItems);
Note that there's no need to pass along the this context.
Another option is to flatMap to extract all rows to a single array first:
const output = data
.flatMap(({ rows }) => rows)
.filter(({ name }) => name === 'TEST$$');

How to get JSON keys and add extra fields?

I'm trying to get the key of these json objects in order to create a new object with extra filed to create table headers in a React app. JSON data:
let example = [
{
id: 1,
city: 'New York',
},
{
id: 2,
city: 'Paris',
},
]
The function:
getKeys() {
return example.map((key) => {
return {
cityName: key, // gets the whole array
capital: false,
};
});
}
I tries Object.keys( example);, it returns integers; 0, 1.
How can I get the keys in this case? Thanks.
You are trying to map the keys for an array since example is an array. If the data are consistent throughout the array get the first element example[0] and do Object.keys().
So Object.keys(example[0])
There's no need to get the keys if you just want to add a property to the items in the array. I think there's a misunderstanding about .map, which gives you a single item/object in the array, not the keys.
Something like this perhaps?
let example = [{
id: 1,
city: 'New York',
}, {
id: 2,
city: 'Paris',
}];
const modifiedArray = function(arr) {
return arr.map(item => {
return {
id: item.id,
cityName: item.city,
capital: false,
};
})
}
const newArray = modifiedArray (example);
console.log(newArray )

Categories

Resources