I have a Rest API which returns data in json of the form :
["1.6.3","1.6.4","1.6.5","1.6.6","1.7.0","1.7.2"]
I need the data in this format:
var options = [{ value: 'one', label: 'One' }, { value: 'two', label: 'Two', clearableValue: false }
];
After fetching the data I am using the following code to map the data in the required format:
if (this.state.coreversions) {
var options = [
this.state.coreversions.map(versions =>
`{ value: '${versions}', label: '${versions}' },`
)
];
}
Here the variable version is equal to a single value of the data returned by the Rest API
Any help would be appreciated.
Array#map returns an array, therefore you do not have to enclose it within square brackets.
Amend your code as follows:
if (this.state.coreversions) {
var options = this.state.coreversions.map(
versions => ({value: versions, label: versions})
);
}
// simplified this.state.coreversions to just coreversions
// only for the purposes of this snippet
var coreversions = ["1.6.3","1.6.4","1.6.5","1.6.6","1.7.0","1.7.2"];
if (coreversions) {
var options = coreversions.map(
versions => ({value: versions, label: versions})
);
}
console.log(options);
// logs out an array of objects:
// [
// { value: '1.6.3', label: '1.6.3' },
// { value: '1.6.4', label: '1.6.4' },
// { value: '1.6.5', label: '1.6.5' },
// { value: '1.6.6', label: '1.6.6' },
// { value: '1.7.0', label: '1.7.0' },
// { value: '1.7.2', label: '1.7.2' }
// ]
I think your map function is returning an array of strings instead of objects. Should be like:
return { value: '${versions}', label: '${versions}' }
Note how the above does not have the ticks surrounding the entire line.
React-Select expects an array of objects, not an array of strings.
You can loop through the data, put these values in a object and push it in an array like the following:
var results = ["1.6.3", "1.6.4", "1.6.5", "1.6.6", "1.7.0", "1.7.2"];
var selectData= [];
for (result of results) {
selectData.push({
value: result,
label: result
});
}
console.log(selectData);
Related
i have a json code coming as:
{
"rID": "1",
"rFI": "01",
"rTN": "0011",
"rAN": "11",
"sID": "2",
"sFI": "004",
"sTN": "1002",
"sAN": "03402"
}
I am using vue JS
currently if i have no api, i am doing this as array of objects in data as;
return
rItems: [
{ label: 'r', value: '01' },
{ label: 'rFN', value: '001' },
{ label: 'rTN', value: '00011' },
{ label: 'rAN', value: '11255' }
],
sItems: [
{ label: 's', value: '01' },
{ label: 'sFN', value: '001' },
{ label: 'sTN', value: '00011' },
{ label: 'sAN', value: '11255' }
],
and using a loop to display data, both rItems and sItems are in seperate divs
like this
<div class=" v-for="item in sItems">
<span class="label">
{{ item.label}}
</span>
<span class="value">
{{ item.value }}
</span>
</div>
same as rItems i have a separate div
now i have created a API file adn want this code to be computed so i can split the json into two seperate and create an array of objects or maybe other way and loop over them
how can i do it, any idea will be helpful
thanks
Assuming you already know how to fetch your data from your API, the final result would be something like this :
const getDataAndSplit = async () => {
const myData = await fetch(URL, etc etc); // get your data from your API
const rItems = []; // declaring empty array to fill it later
const sItems = []; // same
// looping over array of key/values
Object.entries(myData).forEach(([key, val]) => {
if (val.startsWith('r'))
rItems.push({label: key, value: val});
else
sItems.push({label: key, value: val});
}
return {rItems, sItems};
}
I have the data of the array object in a variable called hi[0].child.
hi[0].child = [
{code: "food", name: "buger"},
{code: "cloth", name: "outher"},
{code: "fruit", name: "apple"},
]
What I want to do is create a variable called hello, change the key value of hi[0].child, and put it in the hello variable.
For example, the key value of code is changed to value and name is changed to label. The values I want are as below.
expecter answer
hello = [
{label: "burger", value: "food"},
{label: "outher", value: "cloth"},
{label: "apple", value: "fruit"},
]
But when I use my code I get these errors.
Did not expect a type annotation here
so How can i fix my code?
this is my code
let hello = []
hi[0].child.map((v) => {
hello.push(label: v.name, value: v.code)
})
You've missed the curly brackets for the object, it should be hello.push({ label: v.name, value: v.code }).
Also, map is not the right method to be used here, use forEach instead or use the value returned from map (as shown below).
const data = [
{ code: "food", name: "buger" },
{ code: "cloth", name: "outher" },
{ code: "fruit", name: "apple" },
];
const updatedData = data.map((v) => ({ label: v.code, value: v.name }));
console.log(updatedData);
Change the code like this
let hello = []
hi[0].child.map((v) => {
hello.push({label: v.name, value: v.code})
})
You need to pass object
I am new to typescript. please help to push the data so here it goes
Here the story goes I have string array and i need to push it to the json object
interface LocalIds {
value: string;
label: string;
}
const localIds = [
{ value: 'test', label: 'test' },
{ value: 'test2', label: 'test2' },
];
////////////// HERE in string array that data is coming ///////////
const localIdentifiers: string[] = result.data.map((item: string) => item);
///////////// I want to push the string array data to json object with label & value//////
// I experimented alot but giving some type error and all I am not getting
localIds.push({ label: 'abc', value: 'abc' });
localIdentifiers.map(i => localIds.push(...localIds:{value:i,label:i}[])); //ERROR
Half of your code does nothing useful
result.data.map((item: string) => item) will do nothing
using map when not returning anything inside it is pointless. At very least use forEach instead. or even better....
You should use map with concat:
interface LocalIds {
value: string;
label: string;
}
const localIds = [
{ value: 'test', label: 'test' },
{ value: 'test2', label: 'test2' },
];
localIds.push({ label: 'abc', value: 'abc' });
const finalLocalIds = localIds.concat( result.data.map((i: string) => ({value:i,label:i})) );
Live example
Try fixing last line as following
replace ; with , and remove [] at the end
localIdentifiers.map(i => localIds.push(...localIds, {value:i,label:i}));
also, you dont need ...localIds, since it will duplicate current array every time element is pushed to array
allInfo.map((name) => console.log("arr", name.firstName))
The above statement is an array. I want to iterate the values and put them in the following array to show it in the dropdown.
const info = [
{ value: "firstName", label: "firstName" },
{ value: "first",label: "first"},
{ value: "lastName", label: "lastName" }
]
I want to iterate the value of allInfo and put it inside the value of info. Instead of value = "firstName", I want to get it from the allInfo array. Can anyone help me with this?
Just map the allInfo array directly to get the info array.
const info = allInfo.map(name => ({
value: name.firstName,
label: name.firstName,
}));
If you want to have some static values in the info array too, you can use the spread operator like this:
const allInfoItems = allInfo.map(name => ({
value: name.firstName,
label: name.firstName,
}));
const info = [
{ value: 'something', label: 'something' },
...allInfoItems
]
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 9 months ago.
I'm running an express.js app that has a few apis feeding data to dropdown boxes. The data returned is in the form:
[
{
key: 'blah',
value: 'Blah Blah'
},
{
key: 'foo',
value: 'Foos'
},
{
key: 'bar',
value: 'Bars'
},
{
key: 'baz',
value: 'Bazingo'
}
];
where key is my option key and value is the display text. The structure of this array is fixed and I know for a fact that I'll always have key and value as the fields in each object in the array.
When I try to validate the form submitted (additional server side validation), I'd like to cross-reference the value provided for a field against all the values for "key" in the array (blah, foo, bar, baz). Given that this is going to be a frequently used route, I'd like to avoid iterating over the array to find the permitted values, every single time. Is there a simpler way to do this? In other words, I know I can use:
permittedValues = [];
for (i = 0; i < array.length; i++){
permittedValues[i] = array[i]["key"];
}
but I'd like to avoid this for loop, if possible.
P.S: This seems to be a fundamental question and the answers I found online didn't exactly answer my question. So, apologies if this has already been asked and answered.
You could map:
permittedValues = array.map(function(value) {
return value.key;
});
In ES6/ES2015 it's even prettier with arrow functions:
permittedValues = array.map(value => value.key);
It might be prettier, but it's probably not faster than a for() loop.
Using lodash,
Since lodash 4.x the _.pluck function has been removed in support to map function.
so you can achieve the desired task by:
import _ from 'lodash'
_.map(items, 'key');
Ref: What happened to Lodash _.pluck?
Pure Javascript ES6
array.map(value => value.key);
Underscore/Lodash
_.map(value,'key')
If you are using ES6 javascript version you can do something like the one below:
const arrayData = [
{
key: 'blah',
value: 'Blah Blah'
},
{
key: 'foo',
value: 'Foos'
},
{
key: 'bar',
value: 'Bars'
},
{
key: 'baz',
value: 'Bazingo'
}
];
const foodBar = arrayData.find(item => item.key === "baz");
const resultValue = foodBar['value']; // here the extracted value is by key
In the current versions of Javascript you need a loop do to it.
However you can use a module like npm `lodash' to make it look simpler
var _ = require('lodash')
var permittedValues = _.pluck(array, 'key')
link to pluck documentation
You could extract the values via map, and form them into a regex to match values against.
Example: http://repl.it/X0V
var items=
[
{
key: 'blah',
value: 'Blah Blah'
},
{
key: 'foo',
value: 'Foos'
},
{
key: 'bar',
value: 'Bars'
},
{
key: 'baz',
value: 'Bazingo'
}
];
var toReg = items.map(function(obj){
return obj.key;
}).join('|');
var regex = new RegExp('^('+ toReg +')$');
//To test the regex
var itemsToTest = ['blah', 'Pies', 'foo', 'Bazingo'];
itemsToTest.forEach(function(key){
if(regex.test(key)){
console.log(key);
}
});
Try this..
const myArray = [
{
key: 'blah',
value: 'Blah Blah'
},
{
key: 'foo',
value: 'Foos'
},
{
key: 'bar',
value: 'Bars'
},
{
key: 'baz',
value: 'Bazingo'
}
];
const resObject = myArray.find(item => item.key === "foo");
// Here you can access object which you want
console.log(resObject);
Also you can refer this answer..
Find object by id in an array of JavaScript objects