This question already has answers here:
Convert array of object to object with keys
(2 answers)
Closed 6 years ago.
One of the possible outputs for my service is as follows.
[{
"key": 1,
"val": 0
}, {
"key": 2,
"val": 0
}]
Is there a function that can convert this to an object like the one below?
{
"1":0,
"2":0
}
My purpose is to be able to read the object values as a map, such as o["1"], i.e.: if (o["1"] == 0) {....
You can do this with reduce
var data = [{"key": 1, "val": 0}, {"key": 2, "val": 0}];
var result = data.reduce((obj, e) => {
obj[e.key]= e.val;
return obj;
}, {});
console.log(result)
You could iterate over with Array#forEach and assign the wanted properties with the value.
var array = [{ "key": 1, "val": 0 }, { "key": 2, "val": 0 }],
object = {};
array.forEach(function (a) {
object[a.key] = a.val;
});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
You can do it in javascript with
target = {};
source.forEach(function(e) {
target[e.key] = e.val;
});
I don't think there is one in pure Javascript. Maybe some library like jQuery will have something like that. You can do your own with little code, though. In pure JS:
var o = {};
for (var i = 0; i < json.length; i++) {
o[json[i].key] = json[i].val;
}
Related
I have an array that I'm retrieving from an API. The array looks like this:
[{
"name": "Rachel",
"count": 4,
"fon": "46-104104",
"id": 2
},
{
"name": "Lindsay",
"count": 2,
"fon": "43-053201",
"id": 3
},
{
"name": "Michael",
"count": 5,
"fon": "46-231223",
"id": 4
}]
Then I loop through the array to create an array containing only the names.
function buildName(data) {
for (var i = 0; i < data.length; i++) {
nameList.push(data[i].name)
}
}
This also works so far, but I would like to create an array in which each name occurs as often as the object count says.
For example, the name Michael should appear five times in the array and Lindsay twice.
[
"Rachel",
"Rachel",
"Rachel",
"Rachel",
"Lindsay",
"Lindsay",
"Michael",
"Michael",
"Michael",
"Michael"
"Michael"
]
For each object create a new array using count, and then fill it with the name.
If you use flatMap to iterate over the array of objects. It will return a new array of nested objects but then flatten them into a non-nested structure.
const data=[{name:"Rachel",count:4,fon:"46-104104",id:2},{name:"Lindsay",count:2,fon:"43-053201",id:3},{name:"Michael",count:5,fon:"46-231223",id:4}];
const out = data.flatMap(obj => {
return new Array(obj.count).fill(obj.name)
});
console.log(out);
I've upgraded your functions but you can use the map method
function buildName(data){
for (let i = 0; i < data.length; i++){
let numToLoop = data[i].count
let name = data[i].name
for (let z = 0; z < +numToLoop; z++){
nameList.push(name)
}
}
}
Use an inner while loop inside the for loop:
const data = [{
"name": "Rachel",
"count": 4,
"fon": "46-104104",
"id": 2
},
{
"name": "Lindsay",
"count": 2,
"fon": "43-053201",
"id": 3
},
{
"name": "Michael",
"count": 5,
"fon": "46-231223",
"id": 4
}]
function buildName(data){
const result = [];
for (let i = 0; i < data.length; i += 1) {
let item = data[i];
let count = item.count;
while (count > 0) {
result.push(item.name);
count -= 1;
}
}
return result;
}
console.log(buildName(data));
Just add an inner loop with as many iterations as the "count" property in the object:
function buildName(data) {
const nameList = [];
for (var i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].count; j++) {
nameList.push(data[i].name);
}
}
return nameList;
}
For fun
import { pipe } from 'fp-ts/lib/function';
import { chain, replicate } from 'fp-ts/lib/Array';
const arr = ...
const result = pipe(
arr,
chain(i => replicate(i.count, i.name))
);
You can use .flapMap() for that:
const arr = [{ "name": "Rachel", "count": 4, "fon": "46-104104", "id": 2 }, { "name": "Lindsay", "count": 2, "fon": "43-053201", "id": 3 }, { "name": "Michael", "count": 5, "fon": "46-231223", "id": 4 }];
const result = arr.flatMap(({count, name}) => Array(count).fill(name));
console.log(result);
Effectively you turn every element into an array of the the name property repeated count times which is then flattened into a single array.
It can be done via creating an array with repeated names in this way:
Array(count).fill(name)
Then you have to spread it into resulting array.
You can try this one-liner
const getNames = (data) =>
data.reduce(
(names, { name, count }) => [...names, ...Array(count).fill(name)],
[]
)
Note that a pure function is presented here, which is generally the preferred way of writing code. However, updating your example code might look like this
const getNames = (data) =>
data.reduce(
(names, { name, count }) => [...names, ...Array(count).fill(name)],
[]
)
function buildName(data) {
nameList = getNames(data)
}
This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 4 years ago.
{
"list": [{
"name": "car",
"status": "Good",
"time": "2018-11-02T03:26:34.350Z"
},
{
"name": "Truck",
"status": "Ok",
"time": "2018-11-02T03:27:23.038Z"
},
{
"name": "Bike",
"status": "NEW",
"time": "2018-11-02T13:08:49.175Z"
}
]
}
How do I remove just the car info from the array.
To achieve expected result, use filter option to filter out car related values
var obj = {"list":[ {"name":"car", "status":"Good", "time":"2018-11-02T03:26:34.350Z"}, {"name":"Truck", "status":"Ok", "time":"2018-11-02T03:27:23.038Z"}, {"name":"Bike", "status":"NEW", "time":"2018-11-02T13:08:49.175Z"} ]}
let result = {
list: []
}
result.list.push(obj.list.filter(v => v.name !=='car'))
console.log(result)
codepen - https://codepen.io/nagasai/pen/MzmMQp
Option 2: without using filter as requested by OP
Use simple for loop to achieve same result
var obj = {"list":[ {"name":"car", "status":"Good", "time":"2018-11-02T03:26:34.350Z"}, {"name":"Truck", "status":"Ok", "time":"2018-11-02T03:27:23.038Z"}, {"name":"Bike", "status":"NEW", "time":"2018-11-02T13:08:49.175Z"} ]}
let result = {
list: []
}
for(let i =0; i< obj.list.length; i++){
if(obj.list[i].name !== 'car' ){
result.list.push(obj.list[i])
}
}
console.log(result)
const obj = JSON.parse(jsonString);
let yourArray = obj.list;
let filteredArray = yourArray.filter(elem => elem.name !== "car");
This question already has answers here:
Comparing two arrays of objects, and exclude the elements who match values into new array in JS
(6 answers)
Closed 5 years ago.
I want to find unique elements in a which do not exist in b on the basis of name property
EXPECTED OUTPUT
var data= [{"name":"rashffffish","color":"blue" }];
var a =[{"name":"sam","color":"red" }, {"name":"rash","color":"blue" },{"name":"rashffffish","color":"blue" }];
var b = [{"name":"sam","color":"red" },{"name":"rash","color":"red" }];
var data = [];
b.map((n)=>{
for(i=0;i<a.length;i++) {
if(n.name!= a[i].name){
data.push(a[i]);
}
}
})
console.log(data);
Use Array#filter to filter the a array and pass a predicate which uses Array#some to try to find an item. When there is no match, get those items
const a =[
{"name":"sam","color":"red" },
{"name":"rash","color":"blue" },
{"name":"rashffffish","color":"blue" }
];
const b = [
{"name":"sam","color":"red" },
{"name":"rash","color":"red" }
];
const filtered = a.filter(itemA => !b.some(itemB => itemA.name === itemB.name));
console.log(filtered);
From your code...
var a = [{
"name": "sam",
"color": "red"
}, {
"name": "rash",
"color": "blue"
}, {
"name": "rashffffish",
"color": "blue"
}];
var b = [{
"name": "sam",
"color": "red"
}, {
"name": "rash",
"color": "red"
}];
var data = a;
b.forEach((n) => {
for (i = 0; i < data.length; i++) {
if (n.name === a[i].name) {
var ind= data.indexOf(a[i]);
data.splice(ind, 1);
}
}
})
console.log(data);
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)
I'm trying to process a json file and create a new one, but it does not work.
The structure of an old json is something like this:
[
{
"3":{
"value":2
},
"4":{
"value":1
}
},
{
"3":{
"value":6
},
"4":{
"value":1
}
}...and so on
What I'm trying to do is to create a new json object, which will have only two objects 0 and 1 and inside each of them there will be values from indexes 3 and 4 from the old one, which should look something like this:
{
"0":{
"0":[
{
"0":2
}
],
"1":[
{
"0":6
}
]..and so on
},
"1":{
"0":[
{
"0":1
}
],
"1":[
{
"0":1
}
]..and so on
}
}
The problem is that when I process and cook the old json the output for both indexes(0,1) is the same. I'm trying to loop it through 3 and 4 and assign those values into the new array but something is not quite right.
Fraction of the code:
//loop through the keysIndex
for (var c in keysIndex) {
//the new json has to be 2 objects, hence the below
newData[c] = {};
var vallueArr = [];
var newObj = {
0: oldData[i][keysIndex[c]].value
}
vallueArr.push(newObj);
objInNewData[entries] = vallueArr;
//the problem is somehwere here, it is appending twice the same
//objInNewData and not both 3 and 4 individually
newData[c] = objInNewData;
}
Hers's the whole logic: PLUNKER
Can someone please help as I cannot get my head around this :(
Many thanks
As I mentioned above, the use of index of keys of objects is not a good idea, because objects in Javascript have no defined order. For ordered items I suggest to use an array instead.
var data = [
{
"3": { "value": 2 },
"4": { "value": 1 }
}, {
"3": { "value": 6 },
"4": { "value": 1 }
}
],
keys = Object.keys(data[0]), // <-- ATTENTION!
obj = {};
data.forEach(function (a, i) {
keys.forEach(function (k, j) {
obj[j] = obj[j] || {};
obj[j][i] = obj[j][i] || [];
obj[j][i].push({ '0': a[k].value });
});
});
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');