convert array into an array of ojects - javascript

I have the following array list.
var data = [ "USA", "Denmark", "London"];
I need to convert it in this form
var data = [
{ "id" : 1, "label": "USA" },
{ "id" : 2, "label": "Denmark" },
{ "id" : 3, "label": "London" }
];
Can anyone please let me know how to achieve this.

Pretty easy using Array.map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
var formatted = data.map(function(country, index) {
return { id: (index + 1), label: country }
});

Simple version:
var convertedData = []
for (var i in data){
convertedData.push({id: i+1, label: data[i]});
}
data = convertedData; //if you want to overwrite data variable

You can use forEach to loop through the data array
var data = [ "USA", "Denmark", "London"];
var demArray =[];
data.forEach(function(item,index){
demArray.push({
id:index+1,
label:item
})
})
console.log(demArray)
JSFIDDLE

Underscore way (for old browsers without Array.map support):
var res = _.map(data, function(p, i){
return {id: i + 1, label: p};
});

Related

Create JSON dynamically with dynamic keys and values in Express Js

I am fetching API into my Express server which has several JSON key value pairs in one array.
For Example:
[{
"quality": "best",
"url": "https://someurlhere.example/?someparameters"
},
{
"quality": "medium",
"url": "https://someurlhere1.example/?someparameters"
}]
And I want to create an array of JSON of that received data in this Format:
[{
"best": "https://someurlhere.example/?someparameters"
},
{
"medium": "https://someurlhere1.example/?someparameters"
}]
I have tried doing this by using for loop
for(let i=0; i < formats.length; i++){
arr.push({
`${formats[i].quality}` : `${formats[i].url}`
})
}
But it didn't work for me.
Please help me in achieving this.
Thanks in Advance :)
You could use the map function and create a new object from it.
For example:
let prevArr = [{
"quality": "best",
"url": "https://someurlhere.example/?someparameters"
}, {
"quality": "medium",
"url": "https://someurlhere1.example/?someparameters"
}]; // Replace with your array
let newArr = [];
let obj = {};
prevArr.map(function(x) {
obj = {};
obj[x["quality"]] = x.url;
newArr.push(obj);
});
const input = [{
"quality": "best",
"url": "https://someurlhere.example/?someparameters"
}, {
"quality": "medium",
"url": "https://someurlhere1.example/?someparameters"
}];
const result = input.map((v, i) => {
return {
[v["quality"]]: v["url"]
}
});
console.log(result)

Combine array of objects, combine key with same value and keep unique value

This is my data with 5 arrays. What I wish to achieve is to combine id and name and the new array should have 5 different playname values. It can be in either an array or new key like playername1.
[
{
"id": 1,
"name": "Liquid",
"playername": "GH",
},
{
"id": 1,
"name": "Liquid",
"playername": "KuroKy",
},
{
"id": 1,
"name": "Liquid",
"playername": "Miracle",
},
{
"id": 1,
"name": "Liquid",
"playername": "w33",
},
{
"id": 1,
"name": "Liquid",
"playername": "Mind-Control",
}
]
I am using lodash to try and achieve this but I am not able to get the data format I want using the code examples I have searched online.
This is my current code that I have tried that gives an array that is grouped by the ID.
_.forOwn(this.state.teamsData, function(value, key) {
console.log(value);
});
The original data are not grouped by ID.
I am trying to get my data to look like this {"id": 1, "name": liquid, "playername": "GH", "playername2": "KuroKy" ....}
You could group by id and name properity and store the index for the same group.
var data = [{ id: 1, name: "Liquid", playername: "GH" }, { id: 1, name: "Liquid", playername: "KuroKy" }, { id: 1, name: "Liquid", playername: "Miracle" }, { id: 1, name: "Liquid", playername: "w33" }, { id: 1, name: "Liquid", playername: "Mind-Control" }],
result = Object
.values(data.reduce((r, { id, name, playername }) => {
var key = [id, name].join('|');
r[key] = r[key] || { data: { id, name }, index: 0 };
r[key].data['playername' + (r[key].index++ || '')] = playername;
return r;
}, {}))
.map(({ data }) => data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Group by a combination of id and name (${o.id}~~~${o.name}). Map the groups, extract the name and id from the 1st item, take the player names, and use _.mapKeys() to convert the indexes to object keys. Combine the id, name, and playername properties to a single object using spread.
const teamsData = [{"id":1,"name":"Liquid","playername":"GH"},{"id":1,"name":"Liquid","playername":"KuroKy"},{"id":1,"name":"Liquid","playername":"Miracle"},{"id":1,"name":"Liquid","playername":"w33"},{"id":1,"name":"Liquid","playername":"Mind-Control"}]
const result = _(teamsData)
.groupBy(o => `${o.id}~~~${o.name}`) // group by id and name
.map(group => ({ // map the groups
..._.pick(_.head(group), ['id', 'name']), // take id and name from 1st item
..._.mapKeys(_.map(group, 'playername'), // extract the player names
(v, k) => `playername${+k > 0 ? +k + 1 : ''}` // create the keys
)
}))
.value()
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
You can use reduce and Map. Here Map is used to keep track of number of palyername is used for particular id
const arr = [{"id":1,"name":"Liquid","playername":"GH"},{"id":1,"name":"Liquid","playername":"KuroKy"},{"id":1,"name":"Liquid","playername":"Miracle"},{"id":1,"name":"Liquid","playername":"w33"},{"id":1,"name":"Liquid","playername":"Mind-Control"}]
let groupData = (arr) => {
let mapper = new Map()
return Object.values(arr.reduce((op,{id, name, playername }) => {
mapper.set(id, ( mapper.get(id) || 0) + 1 )
let key = mapper.get(id)
op[id] = op[id] || { id, name }
op[id][`playername${key}`] = playername
return op
},{}))
}
console.log(groupData(arr))
Just using using reduce to group the array into an object and Object.values to convert the object into an array.
let list = [
{"id": 1,"name": "Liquid","playername": "GH",},
{"id": 2,"name": "Solid","playername": "KuroKy",},
{"id": 1,"name": "Liquid","playername": "Miracle",},
{"id": 1,"name": "Liquid","playername": "w33",},
{"id": 2,"name": "Solid","playername": "Mind-Control",}
];
let counter = {};
let result = Object.values(list.reduce((c, v) => {
if (!c[v.id]) {
counter[v.id] = 0;
c[v.id] = {...v};
} else c[v.id]["playername" + ++counter[v.id]] = v.playername;
return c;
}, {}));
console.log(result);
The data could have been structured better. With the given structure, following code is one way to solve it.
let data = [
{"id": 1,"name": "Liquid","playername": "GH",},
{"id": 2,"name": "Solid","playername": "KuroKy",},
{"id": 1,"name": "Liquid","playername": "Miracle",},
{"id": 1,"name": "Liquid","playername": "w33",},
{"id": 2,"name": "Solid","playername": "Mind-Control",}
]; // Your data
let new_data = {}; // New structured data
data.map(function(data_object) {
let team = new_data['id'+data_object.id];
if(team==null) {
// Creates a new object in new_data if an object
// for the id does not exists.
new_data['id'+data_object.id] = team = {};
team.players = [];
}
team.id = data_object.id;
team.name = data_object.name;
team.players.push(data_object.playername);
});
console.log(new_data);
With this code, you will have a new_data object of format
{
id1 : {
id : 1,
name : Liquid,
players : ['GH', 'Miracle', 'w33']
},
id2 : {
id : 2,
name : Solid,
players : ['Kuroky', 'Mind-control']
}
}

Filter array of objects by multiple properties and values

Is it possible to filter an array of objects by multiple values?
E.g in the sample below can I filter it by the term_ids 5 and 6 and type car at the same time?
[
{
"id":1,
"term_id":5,
"type":"car"
},
{
"id":2,
"term_id":3,
"type":"bike"
},
{
"id":3,
"term_id":6,
"type":"car"
}
]
Definitely up for using a library if it makes it easier.
You can do it with Array.filter
var data = [{
"id": 1,
"term_id": 5,
"type": "car"
},
{
"id": 2,
"term_id": 3,
"type": "bike"
},
{
"id": 3,
"term_id": 6,
"type": "car"
}
];
var result = data.filter(function(v, i) {
return ((v["term_id"] == 5 || v["term_id"] == 6) && v.type == "car");
})
console.log(result)
The following function will help you out.
nestedFilter = (targetArray, filters) => {
var filterKeys = Object.keys(filters);
return targetArray.filter(function (eachObj) {
return filterKeys.every(function (eachKey) {
if (!filters[eachKey].length) {
return true;
}
return filters[eachKey].includes(eachObj[eachKey]);
});
});
};
Use this function with filters described as below:
var filters = {
"id": ["3"],
"term_id": ["6"],
"type": ["car","bike"]
}
Dont pass empty array. If there are no values in the array, skip that property in the filters.
The result will be filtered array.
You can do this with plain js filter() method and use && to test for both conditions.
var data = [{"id":1,"term_id":5,"type":"car"},{"id":2,"term_id":3,"type":"bike"},{"id":3,"term_id":6,"type":"car"}];
var result = data.filter(function(e) {
return [5, 6].includes(e.term_id) && e.type == 'car'
});
console.log(result);
Another way to do it is to use lodash filter + reduce.
const arr = [{"id":1,"term_id":5,"type":"car"},{"id":2,"term_id":3,"type":"bike"},{"id":3,"term_id":6,"type":"car"}];
const result = [
{term_id: 5, type: 'car'},
{term_id: 6, type: 'car'},
].reduce((prev, orCondition) => prev.concat(_.filter(arr, orCondition)), []);
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.21/lodash.min.js"></script>

Add a key to each value in json array javascript

I would like to transform the below JSon. The input JSon array can be of any size. I know its a basic question but I can't find the duplicate.
var input = [{
"value": 1
}, {
"value": 2
}]
var output = [{
"key": {
"value": 1
}
}, {
"key": {
"value": 2
}
}]
Appreciate all the help.
Create a new array and use Array#forEach to push an object with key = key and a currently iterated object from input as the value.
var input = [{value:1},{value:2}],
result = [];
input.forEach(v => result.push({ 'key': v }));
console.log(result);
Try using this, this should solve your problem
output = input.map(value => ({ "key": value }) );
console.log(output);
I used ES6 for simplicity, but this does exactly the same.
I think this will be the most oldschool and hands-on way of doing this.
var input = [{
"value": 1
}, {
"value": 2
}],
output = [],
newItem,
i = 0, ii = input.length;
for(i; i<ii; i++){
newItem = {};
newItem.key = {"value":input[i].value};
output.push(newItem);
}
console.log(output)

Get parent array key in deep nested object using lodash

I'm using Lodash JavaScript library in my project and have a problem in getting the parent array key object filtered object:
I've the following data:
var data = {
5: [{
id: "3",
label: "Manish"
}, {
id: "6",
label: "Rahul"
}, {
id: "7",
label: "Vikash"
}],
8: [{
id: "16",
label: "Pankaj"
}, {
id: "45",
label: "Akash"
}],
9: [{
id: "15",
label: "Sunil"
}]
}
My requirement is if I've the array of [6,16] then I want a new result array containing values 5,8 because these two array keys have objects which contain id:"6" and id:"16"
I tried it using _.flatten and _.pick method but could not work. I used the following code;
var list = [];
_.each(data, function(item){
list.push(_.omit(item, 'id'));
list.push(_.flatten(_.pick(item, 'id')));
});
var result = _.flatten(list);
console.log(result);
var res = _([6, 16]).map(function(id){
return _.findKey(data, function(arr){
return _.some(arr, {id: new String(id)});
})
}).compact().uniq().value();
If simple javascript solution is okay with you then
var searchId=[6,16];
var newArr = [];
for ( key in data ){
data[key].forEach( function(innerValue){
if ( searchId.indexOf( Number(innerValue.id) ) != -1 ) newArr.push( key );
} );
}
console.log(newArr);
try this:
( hope im not missing some syntax )
var result = [];
var filterArray = [6,16];
_.each(filterArray, function(item){
_.merge(result,_.filter(data, function(o) { return _.contains(o,{id:item}) }));
});
Using _.pickBy this problem is solved simply:
var myArr = [6, 16]
var res = _.pickBy(data, function (value) {
return _(value).map('id').map(_.toNumber).intersection(myArr).size();
});
console.log(res)
https://jsfiddle.net/7s4s7h3w/

Categories