I have a javascript variable, call it temp, that is holding value input by a user. For example,
const temp=10
I want to update an object property to this variable value.
For example, I want to change
var data = [
{
"1": "1.5",
"2": "2",
"subject_input": "null",
"entry": 1
}
]
to
var data = [
{
"1": "1.5",
"2": "2",
"subject_input": value of the javascript variable 'temp',
"entry": 1
}
]
I've tried just including the variable like this:
var data = [
{
"1": "1.5",
"2": "2",
"subject_input": "temp",
"entry": 1
}
]
and this
var data = [
{
"1": "1.5",
"2": "2",
"subject_input": temp,
"entry": 1
}
]
and neither worked. Is there an easy way to do this?
var data = [{"1":"1.5","2":"2","subject_input":"null","entry":1}]
const temp = "temp data";
data = data.map(o => ({...o, subject_input: temp}));
console.log(data);
//or directly assigning temp to subject_input
var data2 = [
{
"1":"1.5",
"2":"2",
"subject_input":temp,
"entry":1
}
];
console.log(data2);
Related
I have a data like this in array.
[
{
"teamName": "TeamA",
"players": ["1","2"]
},
{
"teamName": "TeamB",
"players": ["2"]
}
]
and I want to replace players id which match in other array
players = [
{
"id": "1",
"playername": "alex"
},
{
"id": "2",
"playername": "john"
}
]
So output will be like this
[
{
"teamName": "TeamA",
"players": [
{
"id": "1",
"playername": "alex"
},
{
"id": "2",
"playername": "john"
}]
},
{
"teamName": "TeamB",
"players": [
{
"id": "2",
"playername": "john"
}]
}
]
I tried to find by for loop and where it will find and replace but that's not working for me.
you can do this by iterating over first array and updating the players property of each element in that array.
let arrOne = [
{
"teamName": "TeamA",
"players": ["1","2"]
},
{
"teamName": "TeamB",
"players": ["2"]
}
]
players = [
{
"id": "1",
"playername": "alex"
},
{
"id": "2",
"playername": "john"
}
]
// solution
arrOne.forEach( teamObject => {
let newPlayerArray = [];
teamObject.players.forEach( id => {
let newPlayerObject = {};
newPlayerObject.id = id;
newPlayerObject.playername = players.find( player => player.id == id)?.playername;
newPlayerArray.push(newPlayerObject)
})
teamObject.players = newPlayerArray;
})
One approach:
// defining the variables, naming 'teams' as it was unnamed in
// the original post:
let teams = [
{
"teamName": "TeamA",
"players": ["1", "2"]
},
{
"teamName": "TeamB",
"players": ["2"]
}
],
// updated the name of this Array of Objects due to the naming
// clash between the original name ('players') when using
// destructuring assignments while iterating the 'teams' Array,
// because of an identically-named property:
playerDetails = [{
"id": "1",
// I updated this property-name to use camelCase consistently:
"playerName": "alex"
},
{
"id": "2",
"playerName": "john"
}
],
// rather than editing the original Array, we create a new one
// by iterating over the teams Array, using Array.prototype.map():
combined = teams.map(
// using destructuring assignement to retrieve the named properties
// of the Object passed in to the function:
({
teamName,
players
}) => {
// because we're returning an Object literal, we have to use return and wrap
// the anonymous callback function of the Arrow function in curly braces ('{...}')
// to avoid the returned Object-literal being misinterpreted as a function body:
return {
// we return the teamName property unchanged:
teamName,
// but here we update the players property, we iterate over the players Array,
// again using players.prototype.map() to update the existing Array based on the
// result of actions taken in the anonymous Arrow function:
players: players.map(
// we pass in a reference to the 'id' enclosed within the player Array,
// giving it a verbose/clear name given that 'id' would be a sensible/short
// name, but is used within the enclosed function as the named property of
// the other function we're working with.
// within the anonymous function we use Array.prototype.find():
(teams_playerID) => playerDetails.find(({
// passing in a reference to the 'id' property-name of the Object
// within the playerDetails Array:
id
// and here we check to see if the 'id' of the playerDetails Array is
// exactly-equal to the teams_playerID variable; if so this Object is
// returned and the 'players' Array is updated, and changed from a String
// to the found Object; if no match is found the current 'players' Array-value
// is unchanged:
}) => id == teams_playerID ))
}
});
console.log(combined);
// [{"teamName":"TeamA","players":[{"id":"1","playerName":"alex"},{"id":"2","playerName":"john"}]},{"teamName":"TeamB","players":[{"id":"2","playerName":"john"}]}]
JS Fiddle demo.
References:
Array.prototype.find().
Array.prototype.map().
Arrow functions.
Destructuring assignemnt.
You can build the result by stepping through the list of teams, looking up each player by their id, and adding the player record to the result’s players array.
const teams = [
{
"teamName": "TeamA",
"players": ["1", "2"]
},
{
"teamName": "TeamB",
"players": ["2"]
}
]
const players = [
{
"id": "1",
"playername": "alex"
},
{
"id": "2",
"playername": "john"
}
]
let result = []
teams.forEach(team => {
let record = {
"teamname": team.teamName,
"players": []
}
team.players.forEach(player_id => {
record.players.push(players.find(p => p.id === player_id))
})
result.push(record)
})
console.log(JSON.stringify(result, null, 4))
I have below array. First object is the original data. Inside array is the changed value. I am trying to create a final data by matching with the Name field with inside array. which should look like
var a =
[
{"Id":"1","Test":"Name1","Name":"hunt9988ggggggggggggdfsf1111"},
{"Id":"2","Test":"Name2","Name":"hunt9988ggggggggggggdfsf"},
[
**{"Name":"hunt9988ggggggggggggdfsf1118","Id":"1"}, // Changed value
{"Name":"hunt9988ggggggggggggdfsf1118","Id":"2"}**
]
]
Final Data
var a =
[
{"Id":"1","Test":"Name1","Name":"hunt9988ggggggggggggdfsf1118"},
{"Id":"2","Test":"Name2","Name":"hunt9988ggggggggggggdfsf1118"}
]
I am trying with below code
var result = a.map(item => ({ value: item.Id, text: item.Name}));
console.log(result)
Like this?
Note I modify the original array
let a = [{
"Id": "1",
"Test": "Name1",
"Name": "hunt9988ggggggggggggdfsf1111"
},
{
"Id": "2",
"Test": "Name2",
"Name": "hunt9988ggggggggggggdfsf"
},
[{
"Name": "hunt9988ggggggggggggdfsf1118",
"Id": "1"
}, // Changed value
{
"Name": "hunt9988ggggggggggggdfsf1118",
"Id": "2"
}
]
]
const replaceArray = a.find(item => Array.isArray(item))
replaceArray.forEach(item => a.find(aItem => aItem.Id === item.Id).Name=item.Name)
a = a.filter(item => item.Id)
console.log(a)
I have one javascript array and one object . Need help to sort javascript object keys based on the order number in another array
In subgroup array , I have name , order number. Need to sort Offerings keys based on that order number
const subgroup = [
{
"code": "6748",
"name": "test123",
"orderNumber": "0"
},
{
"code": "1234",
"name": "customdata",
"orderNumber": "1"
}
]
const offerings = {
"customdata" : [
{
"code": "Audi",
"color": "black"
}
],
"test123" : [
{
"brand": "Audi",
"color": "black"
}
]
}
I believe this should work for you. I've added some comments in the code that should hopefully do an okay job of explaining what is happening.
var subgroup = [{
"code": "6748",
"name": "test123",
"orderNumber": "0"
}, {
"code": "1234",
"name": "customdata",
"orderNumber": "1"
}];
var offerings = {
"customdata": [{
"code": "Audi",
"color": "black"
}],
"test123": [{
"brand": "Audi",
"color": "black"
}]
}
function sortObjectFromArray(refArray, sortObject, orderKey = 'order', linkKey = 'key') {
// Get copy of refArray
let reference = refArray.slice();
// Sort sortObject [ into an array at this point ]
let sorted = [];
for (let key in sortObject) {
// Searches the refArray for the linkKey, and returns the intended index
let index = reference.find((item) => item[linkKey] === key)[orderKey];
// Places the sortObject's value in the correct index of the 'sorted' Array
sorted[parseInt(index)] = [key, sortObject[key]];
};
// Return an object, created from previous 'sorted' Array
return sorted.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, {});
};
offerings = sortObjectFromArray(subgroup, offerings, 'orderNumber', 'name');
console.log(offerings);
I'm trying to access members in a json, however I am running into some trouble. Here is an example of one of the json objects, stored in var obj:
var fs = require('fs');
var obj = [
{
"_id": "52d7f816f96d7f6f31fbb680",
"regNum": "0361300035313000002",
"sd": "2013-01-01T00:00:00",
"pd": "2013-01-25T09:30:29Z",
"prd": "2012-12-18",
"p": 1395000000,
"pt": [
{
"name": name here",
"price": 1395000000,
"OKDP": {
"code": "5520109",
"name": "name here"
},
"sid": "25484812",
"sum": "1395000000",
"OKEI": {
"code": "796",
"name": "name two"
},
"quantity": "1"
}
],
"b": 0,
"c": 0,
"s": 0
}
];
I'm trying to access the sid and sum values, by doing the following:
var sid = [];
var sum = [];
obj.forEach(block => {
var sidOut = block.pt.sid;
var sumOut = block.pt.sum;
sid.push(sidOut);
sum.push(sumOut);
});
console.log(sid);
console.log(sum);
I tried the solution here, however, when I run these it gives me [ undefined ] errors.
Why am I unable to access this two values?
if you see your pt is an array of an object [{}] so you need to select which element you want to access so
var sidOut = block.pt[0].sid;
var sumOut = block.pt[0].sum;
should get you the right result
My data is currently stored in this format, stored in a JSON file:
{
"name": {
"0": ______,
"1": ______,
"2": ______
},
"xcoord": {
"0": ______,
"1": ______,
"2": ______
},
"ycoord": {
"0": ______,
"1": ______,
"2": ______
}
}
And I need to convert it into this format, as an array of objects:
[
{
"id": 0,
"name": _____,
"xcoord": _____,
"ycoord": _____
},
{
"id": 1,
"name": _____,
"xcoord": _____,
"ycoord": _____
},
{
"id": 2,
"name": _____,
"xcoord": _____,
"ycoord": _____
}
]
As you can see, I also need to take the number keys in my first data format and make them the "id" values in my second data format. (Since the position of the object in the array and the id number match up, maybe that would be another way to create the "id" key?) I would then store my second data format into a local variable to use in my JS code.
Any ideas on how I can do this? I'm not very good with restructuring this kind of data.
This can be done for instance with two imbricated .forEach():
var obj = {
"name": {
0: 'name0',
1: 'name1',
2: 'name2'
},
"xcoord": {
0: 'xcoord0',
1: 'xcoord1',
2: 'xcoord2'
},
"ycoord": {
0: 'ycoord0',
1: 'ycoord1',
2: 'ycoord2'
}
};
var res = [];
Object.keys(obj).forEach(k => {
Object.keys(obj[k]).forEach(v => {
(res[v] = (res[v] || { id: v }))[k] = obj[k][v];
});
});
console.log(res);
Note:
This line ...
(res[v] = (res[v] || { id: v }))[k] = obj[k][v]
... is a short way to do:
if(!res[v]) {
// if this record doesn't exist yet,
// create it with its implied 'id' property
res[v] = { id: v };
}
// add property 'k' to this record
res[v][k] = obj[k][v];