I am receiving an array of strings from a server in the following format:
var fruitsStrings = ["apple", "banana", "orange" ];
Is it possible to convert this into an array of objects, like below?
var fruitsObjects = [
{
fruit: "apple"
},
{
fruit: "banana"
},
{
fruit: "orange"
}
];
All the object properties will be the same. Happy to use pure JavaScript or jQuery. I've tried using jquery.extend but as this adds unique IDs before each value it's not really fit for my purpose.
Thank you.
you can use .map
var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects = fruitsStrings.map(function( val, i ) {
return {fruit:val};
});
document.write(JSON.stringify(fruitsObjects));
var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects = fruitsStrings.map(function( val, i ) {
return {fruit:val};
});
document.write(JSON.stringify(fruitsObjects));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects = [];
fruitsStrings.forEach(function (item) {
fruitsObjects.push({ fruit: item });
});
Working demo.
Try this:
var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects = [];
$.map( fruitsStrings, function( val, i ) {
fruitsObjects.push({ fruits: val });
});
A simple Array.prototype.map will do:
var fruitsStrings = ["apple", "banana", "orange"],
fruitsArray = fruitsStrings.map(function (a) { return { fruit: a } });
document.write('<pre>' + JSON.stringify(fruitsArray, 0, 4) + '</pre>');
You could also use this function where you can specify the key.
function toObjects(key,arr) {
var objects = [];
for (var i = 0; i < arr.length; ++i){
var obj = {};
obj[key] = arr[i];
objects[i] = obj;
}
return objects;
}
var fruitsStrings = ["apple", "banana", "orange" ];
toObjects('fruit',fruitsStrings);
// [{fruit: "apple"},{fruit: "banana"},{fruit: "orange"}]
Try this:
var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects = [];
fruitsStrings.map(function(v,i){
fruitsObjects.push({'fruit':v});
});
console.log(fruitsObjects);
Working Demo
Related
I want to return the object containing the closest strings inside array inside an object, inside another array,
my indexOf() only return the exact string as true.
I tried replacing indexOf() with march(), matches(), includes() nothing works.
Please advice
let SellerList = [
{ supplyList: ["apple", "orange", "red apple"] },
{ supplyList: ["apple juice", "drink", "green apple", "dream app"] },
{ supplyList: ["lamp", "dog", "cat", "man"] }
];
let stringToMatch = "app";
let filteredList = SellerList.filter(
(txt) => txt.supplyList.indexOf(stringToMatch) !== -1
);
the output i wish for is all the objects containing the closest strings for example:
[
{ supplyList: ["apple", "orange", "red apple"] },
{ supplyList: ["apple juice", "drink", "green apple", "dream app"] }
];
You have an array inside an object, inside another array, so you want to target that inner array and call filter on it:
let SellerList = [{
supplyList: ['apple', 'orange', 'red apple']
}];
let stringToMatch = 'app';
let filteredList = SellerList[0].supplyList.filter(txt => txt.indexOf(stringToMatch) !== -1);
console.log(filteredList)
Please try the following solution
let SellerList = [
{ supplyList: ["apple", "orange", "red apple"] },
{ supplyList: ["apple juice", "drink", "green apple", "dream app"] },
{ supplyList: ["lamp", "dog", "cat", "man"] },
];
let stringToMatch = "app";
let filteredList = SellerList.reduce((previousValue, currentValue) => {
if (currentValue.supplyList.join().includes(stringToMatch)) {
previousValue = [...previousValue, { supplyList: currentValue.supplyList }];
}
return previousValue;
}, []);
console.log(filteredList);
See
Array.prototype.reduce()
Array.prototype.join()
You should try to match the inner strings of the supplyLists instead of the arrays themselves.
let SellerList = [
{ supplyList: ['apple','orange','red apple'] },
{ supplyList: ['apple juice','drink','green apple'] }
];
let stringToMatch = 'app';
let filteredList = SellerList.map(list => {
return list.supplyList.filter(item => {
return item.indexOf(stringToMatch) >= 0
})
});
console.log(filteredList);
Sorry I've just changed this question :
I would like to know how many times I have THE WORD "orange" in my array. In this example "orange" > 4 times.
MyArray = [{
fruit1: "Orange is blabla",
fruit2: "Apple blabla",
fruit3: "blabla Banana",
color1: "ORANGE"
}, {
fruit4: "blabla Orange",
fruit5: "Apple",
fruit6: "Banana",
color2: "orange blabla"
}];
var newArr = MyArray.filter(function (item) {
return _.values(item.xxx === "orange";
});
You can do it in the following way
let MyArray = [{fruit1:"Orange", fruit2:"Apple", fruit3:"Banana", color1:"ORANGE"},{fruit4:"Orange", fruit5:"Apple", fruit6:"Banana", color2:"orange"}];
let result = MyArray.reduce((a, b) => {
for(let key of Object.keys(b)){
let re = /orange/gi;
if(b[key].match(re) != null){
a++;
}
}
return a;
}, 0);
console.log(result);
MyArray = [{
fruit1: "Orange is blabla",
fruit2: "Apple blabla",
fruit3: "blabla Banana",
color1: "ORANGE"
}, {
fruit4: "blabla Orange",
fruit5: "Apple",
fruit6: "Banana",
color2: "orange blabla"
}];
var totalOrange = 0;
MyArray.map(function(item) {
for (var key in item) {
if (item[key].toLowerCase().indexOf('orange') >= 0) {
totalOrange++;
}
}
});
console.log(totalOrange);
I guess something like this might work.
You could do it in one big loop to make it slightly faster, but this form in more readable imho.
const amountOfOranges = MyArray
// transform each object into an array of its values
.map( Object.values )
// remove all values not named 'orange'
.map( ary => ary.filter( value => value === 'orange' ) )
// replace all arrays by their length
.map( ary => ary.length )
// sum the results
.reduce( ( x, y ) => x + y, 0 );
var MyArray = [{fruit1:"Orange", fruit2:"Apple", fruit3:"Banana", color1:"ORANGE"},{fruit4:"Orange", fruit5:"Apple", fruit6:"Banana", color2:"orange"}];
var count = 0;
MyArray.map(function(item,index){
Object.keys(item).map(function(key){
if(item[key].toLowerCase().indexOf('orange') >= 0){
count++;
}
});
});
console.log(count);
With ES6 you can use spread syntax ... and Object.values to do this.
var MyArray = [{ fruit1: "Orange is blabla", fruit2: "Apple blabla", fruit3: "blabla Banana", color1: "ORANGE" }, { fruit4: "blabla Orange", fruit5: "Apple", fruit6: "Banana", color2: "orange blabla" }]
var count = [].concat(...MyArray.map(Object.values))
.filter(e => e.toLowerCase().includes('orange'))
.length;
console.log(count)
You can do something like this : -
const count = MyArray.reduce((count,item)=>{
Object.keys(item).forEach((val)=>{
if(item[val].toLowerCase().indexOf('orange') != -1){
count++;
}
})
return count
},0)
I know the title might sounds confusing, but i'm stuck for an hour using $.each. Basically I have 2 arrays
[{"section_name":"abc","id":1},{"section_name":"xyz","id":2}];
and [{"toy":"car","section_id":1},{"tool":"knife","section_id":1},{"weapons":"cutter","section_id":2}];
How do I put one into another as a new property key like
[{
"section_name": "abc",
"id": 1,
"new_property_name": [{
"toy": "car"
}, {
"tool": "knife"
}]
}, {
"section_name": "xyz",
"id": 2,
"new_property_name": [{
"weapon": "cutter"
}]
}]
ES6 Solution :
const arr = [{"section_name":"abc","id":1},{"section_name":"xyz","id":2}];
const arr2 = [{"toy":"car","id":1},{"tool":"knife","id":1},{"weapons":"cutter","id":2}];
const res = arr.map((section,index) => {
section.new_property_name = arr2.filter(item => item.id === section.id);
return section;
});
EDIT : Like georg mentionned in the comments, the solution above is actually mutating arr, it modifies the original arr (if you log the arr after mapping it, you will see it has changed, mutated the arr and have the new_property_name). It makes the .map() useless, a simple forEach() is indeed more appropriate and save one line.
arr.forEach(section => {
section.new_property_name = arr2.filter(item => item.id === section.id));
});
try this
var data1 = [{"section_name":"abc","id":1},{"section_name":"xyz","id":2}];
var data2 = [{"toy":"car","id":1},{"tool":"knife","id":1},{"weapons":"cutter","id":2}];
var map = {};
//first iterate data1 the create a map of all the objects by its ids
data1.forEach( function( obj ){ map[ obj.id ] = obj });
//Iterate data2 and populate the new_property_name of all the ids
data2.forEach( function(obj){
var id = obj.id;
map[ id ].new_property_name = map[ id ].new_property_name || [];
delete obj.id;
map[ id ].new_property_name.push( obj );
});
//just get only the values from the map
var output = Object.keys(map).map(function(key){ return map[ key ] });
console.log(output);
You could use ah hash table for look up and build a new object for inserting into the new_property_name array.
var array1 = [{ "section_name": "abc", "id": 1 }, { "section_name": "xyz", "id": 2 }],
array2 = [{ "toy": "car", "section_id": 1 }, { "tool": "knife", "section_id": 1 }, { "weapons": "cutter", "section_id": 2 }],
hash = Object.create(null);
array1.forEach(function (a) {
a.new_property_name = [];
hash[a.id] = a;
});
array2.forEach(function (a) {
hash[a.section_id].new_property_name.push(Object.keys(a).reduce(function (r, k) {
if (k !== 'section_id') {
r[k] = a[k];
}
return r;
}, {}));
});
console.log(array1);
Seems like by using Jquery $.merge() Function you can achieve what you need. Then we have concat function too which can be used to merge one array with another.
Use Object.assign()
In your case you can do it like Object.assign(array1[0], array2[0]).
It's very good for combining objects, so in your case you just need to combine your objects within the array.
Example of code:
var objA = [{"section_name":"abc","id":1},{"section_name":"xyz","id":2}];
var objB = [{"toy":"car","section_id":1},{"tool":"knife","section_id":1},{"weapons":"cutter","section_id":2}];
var objC = Object.assign({},objA[0],objB[0]);
console.log(JSON.stringify(objC));// {"section_name":"abc","id":1,"toy":"car","section_id":1}
For more info, you can refer here: Object.assign()
var firstArray = [{"section_name":"abc","id":1},{"section_name":"xyz","id":2}],
secondArray = [{"toy":"car","section_id":1},{"tool":"knife","section_id":1},{"weapons":"cutter","section_id":2}];
var hash = Object.create(null);
firstArray.forEach(s => {
hash[s.id] = s;
s['new_property_name'] = [];
});
secondArray.forEach(i => hash[i['section_id']]['new_property_name'].push(i));
console.log(firstArray);
I have the following object:
var object = [
{
"category": "Apple",
"color": "green"
},
{
"category": "Orange",
"color": "Orange"
},
{
"category": "Apple",
"color": "green"
}
];
I am trying to iterate the data via category, so the following would show in a list:
Apple
Apple
Orange
Below is the code I've tried but unfortuantely it shows in the order it appears in the object. Any ideas would be much appreciated.
function makeUL(object) {
var list = document.createElement('ul');
for(var i = 0; i < object.length; i++) {
var item = document.createElement('li');
var a = document.createElement("a");
a.textContent = object[i].category;
a.setAttribute('href', 'http://test');
item.appendChild(a);
list.appendChild(item);
}
return list;
}
A solution with group change:
var object = [{ "category": "Apple", "color": "green" }, { "category": "Orange", "color": "Orange" }, { "category": "Apple", "color": "green" }];
function makeUL(object) {
var div = document.createElement('div');
object.sort(function (a, b) { return a.category.localeCompare(b.category); });
object.forEach(function (aa) {
var a = document.createElement("a"),
item = document.createElement('li'),
p;
if (aa.category !== this.last) {
p = document.createElement('p');
p.innerHTML = aa.category;
div.appendChild(p);
this.list = document.createElement('ul');
div.appendChild(this.list);
this.last = aa.category;
}
a.textContent = aa.category;
a.setAttribute('href', 'http://test');
item.appendChild(a);
this.list.appendChild(item);
}, { last: undefined, list: undefined });
return div;
}
document.body.appendChild(makeUL(object));
You could use Array.sort
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
sort the array before using it in for loop
object.sort(function(a,b){
return a.category > b.category
});
object.sort(function(a, b) {
return a.category > b.category;
});
Result
[ { category: 'Apple', color: 'green' },
{ category: 'Apple', color: 'green' },
{ category: 'Orange', color: 'Orange' } ]
If you want your array to be sorted alphabetically ( DESC order, from A to Z ) you have to call the .sort() method first
function makeUL(object) {
var list = document.createElement('ul');
object.sort();
for(var i = 0; i < object.length; i++) {
var item = document.createElement('li');
var a = document.createElement("a");
while(i<length - 1 && object[i].category == object[i+1].category)
a.textContent += object[i].color + ", ";
a.setAttribute('href', 'http://test');
item.appendChild(a);
list.appendChild(item);
}
return list;
}
How could I use vanilla js or lodash to return Scene.data[i].trends into a one newArr
Output should look like this:
var newArr = superFunction();
console.log(newArr);
=> [{id:100},{id:101},{id:200},{id:201}]
Dataset:
Scenes.data = [
{
id: 0,
trends: [
{
id: 100,
},
{
id: 101,
}]
},
{
id: 2,
trends: [
{
id: 200,
},
{
id: 201,
}]
}]
With lodash you can use pluck and flattern:
var result = _(scenes).pluck('trends').flattern().value();
Or maybe reduce (plain js):
var result = scenes.reduce(function(prev, curr) {
return prev.concat(curr.trends);
}, []);
You can do this :
var newArr = [].concat.apply([], Scenes.data.map(function(v){ return v.trends }));
Demonstration
You can do it like this:
var newArr = [];
Scenes.data.forEach(function(x) {
x.trends.forEach(function(trend) {
var obj = {};
for(var key in trend) {
if (trend.hasOwnProperty(key)) {
obj["" + key + ""] = trend[key];
}
}
newArr.push(obj);
});
});
Fiddle