How to convert multiple object indexes into the nested array? - javascript

I have an object that has multiple indexes and each index has different key and value data. Using the data below, how can I convert the data into the following array format?
"result": {
"abc": {
"0": {
"1.0": 126,
"0.9998": 3,
"1.0003": 19
},
"1": {
"1.0": 111,
"0.9997": 4,
"1.0003": 19
},
"2": {
"1.0": 89,
"1.0001": 75,
"0.9998": 5
}
},
"xyz": {
"0": {
"1.0": 1,
"0.9998": 5,
"1.0003": 20
},
"1": {
"1.0": 141,
"0.9997": 56,
"1.0003": 19
},
"2": {
"1.0": 89,
"1.0001": 75,
"0.9998": 5
}
}
}
The desired output that I am looking for is the following:
return [
[126, 3, 19],
[111, 4, 19],
[89, 75, 5],
[1, 5, 20],
[141, 56, 19],
[89, 75, 5]
]
I tried the following but it only returns the zero index in single array:
const values = Object.values(result)
const test = Object.values(...values);
console.log(test)
// [126, 3, 19]

const data = {
"abc": {
"0": { "1.0": 126, "0.9998": 3, "1.0003": 19 },
"1": { "1.0": 111, "0.9997": 4, "1.0003": 19 },
"2": { "1.0": 89, "1.0001": 75, "0.9998": 5 }
},
"xyz": {
"0": { "1.0": 1, "0.9998": 5, "1.0003": 20 },
"1": { "1.0": 141, "0.9997": 56, "1.0003": 19 },
"2": { "1.0": 89, "1.0001": 75, "0.9998": 5 }
}
};
const res = Object.values(data)
.reduce((acc, item) => ([ ...acc, ...Object.values(item) ]), [])
.map(Object.values);
console.log(res);

Use Object.values(), then map with Array.flatMap() to get a flat array of the internal objects, and map again with Array.map() to get just the values:
const data = {"abc":{"0":{"1.0":126,"0.9998":3,"1.0003":19},"1":{"1.0":111,"0.9997":4,"1.0003":19},"2":{"1.0":89,"1.0001":75,"0.9998":5}},"xyz":{"0":{"1.0":1,"0.9998":5,"1.0003":20},"1":{"1.0":141,"0.9997":56,"1.0003":19},"2":{"1.0":89,"1.0001":75,"0.9998":5}}};
const res = Object.values(data)
.flatMap(Object.values)
.map(Object.values);
console.log(res);

Related

How to select random object from JSON file in discord.js

I've done some searching around and I found some posts on here but my code doesn't want to work.
Basically I'm making a discord bot and I want to select an object from a JSON file at random.
This is my command:
const UserData = require('../data/users.js');
const monster = require('../data/monsters.json');
module.exports = {
name: 'battle',
aliases: ['fight'],
cooldown: 0,
description: 'User fights against a monster alone or in group',
execute(client, message, args) {
let enemy = monster[Math.floor(Math.random() * monster.length)]
UserData.findOne({
userID: message.author.id
}, (error, userdata) => {
if (error) console.log(error);
if (!userdata) {
return message.reply(`you don't have an account!`);
} else {
console.log(enemy);
return message.channel.send(`${enemy} spawned!`);
}
})
}
}
And this is my JSON file:
"1" : {
"name": "Blue Slime",
"hp": 20,
"atk": 12,
"def": 10,
"spatk": 3,
"spdef": 12,
"spd": 100,
"gold": 10,
"xp": 50,
"lvl": 1
},
"2": {
"name": "Red slime",
"hp": 20,
"atk": 12,
"def": 10,
"spatk": 3,
"spdef": 12,
"spd": 100,
"gold": 10,
"xp": 50,
"lvl": 1
},
"3": {
"name": "Green slime",
"hp": 20,
"atk": 12,
"def": 10,
"spatk": 3,
"spdef": 12,
"spd": 100,
"gold": 10,
"xp": 50,
"lvl": 1
}
}
If I want put the objects in the command manually and then randomly select them it works and if instead of "monster.length" I put a number then it also works but I still get undefined if it should be 3.
This way I also always get undefined in console log from monster.length.
What am I doing wrong?
Your monsters.json file contains an object and objects don't have lengths. You can however convert it to an array, using Object.values() that returns an array of the given object's own enumerable property values.
Check out the snippet below:
let monsters = {
1: {
name: 'Blue Slime',
hp: 20,
atk: 12,
def: 10,
spatk: 3,
spdef: 12,
spd: 100,
gold: 10,
xp: 50,
lvl: 1,
},
2: {
name: 'Red slime',
hp: 20,
atk: 12,
def: 10,
spatk: 3,
spdef: 12,
spd: 100,
gold: 10,
xp: 50,
lvl: 1,
},
3: {
name: 'Green slime',
hp: 20,
atk: 12,
def: 10,
spatk: 3,
spdef: 12,
spd: 100,
gold: 10,
xp: 50,
lvl: 1,
},
};
function randomObject(obj) {
let arr = Object.values(obj);
return arr[Math.floor(Math.random() * arr.length)];
}
let enemy = randomObject(monsters);
console.log(enemy);

javascript JSON : Sum two or more json having only numeric values with same keys

I am new to Nodejs and typescript.I have below two jsons :
json1 =
{
"201809": 2,
"metric": "headcount",
"quarter1": 60,
"careerLevelsGroups": [{
"201809": 2,
"quarter1": 60,
"careerLevels": [{
"201809": 2,
"careerId": "careerId1",
"quarter1": 60,
},
{
"201809": 2,
"careerId": "careerId2",
"quarter1": 50,
}
]
}]
}
json2 =
{
"201809": 3,
"metric": "headcount",
"quarter1": 100,
"careerLevelsGroups": [{
"201809": 7,
"quarter1": 40,
"careerLevels": [{
"201809": 9,
"careerId": "careerId1",
"quarter1": 30,
},
{
"201809": 8,
"careerId": "careerId2",
"quarter1": 30,
}
]
}]
}
I want to sum all the numeric values associated with the same keys and produce a single json having the summed values of json1 and json2.
result =
{
"201809": 5,
"metric": "headcount",
"quarter1": 160,
"careerLevelsGroups": [{
"201809": 9,
"quarter1": 100,
"careerLevels": [{
"201809": 11,
"careerId": "careerId1",
"quarter1": 90,
},
{
"201809": 10,
"careerId": "careerId2",
"quarter1": 80,
}
]
}]
}
I am trying to use a loop but i have too many such elements which i need to sum so can you please suggest a more optimised method to be used in Node.js
I put together a combine() function which uses recursion for processing members of the JSON object. If it detects a "number" it combines it. If it detects an "object" it applies recursion to search for more "number" or "object" inside it. For any other type (e.g. "string") it just leaves the values as is.
function combine(acc, curr) {
for (var key in acc) {
switch (typeof(acc[key])) {
case "number":
acc[key] += curr[key];
break;
case "object":
combine(acc[key], curr[key]);
break;
}
}
}
var json1 =
{
"201809": 2,
"metric": "headcount",
"quarter1": 60,
"careerLevelsGroups": [{
"201809": 2,
"quarter1": 60,
"careerLevels": [{
"201809": 2,
"careerId": "careerId1",
"quarter1": 60,
},
{
"201809": 2,
"careerId": "careerId2",
"quarter1": 50,
}
]
}]
};
var json2 =
{
"201809": 3,
"metric": "headcount",
"quarter1": 100,
"careerLevelsGroups": [{
"201809": 7,
"quarter1": 40,
"careerLevels": [{
"201809": 9,
"careerId": "careerId1",
"quarter1": 30,
},
{
"201809": 8,
"careerId": "careerId2",
"quarter1": 30,
}
]
}]
};
var res = json1;
combine(res, json2);
console.log(JSON.stringify(json1, undefined, 2));
Running the script produces the desired output. It should be a straightforward execise, to iterate through a series of these JSON objects to generate the result required.

group and restructure json data using javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have this data where I don't have control to format or do any changes
//input json data
[
{
"Breaks":[
{"points":12,"points_total":12,"average":8.0,"faults":[]},
{"points":17,"points_total":29,"average":11.6,"faults":[]},
{"points":6,"points_total":35,"average":11.6667,"faults":[]},
{"points":8,"points_total":43,"average":10.75,"faults":[]},
{"points":14,"points_total":57,"average":11.4,"faults":[]},
],
"team_name":"King Sports"
},
{
"Breaks":[
{"points":18,"points_total":18,"average":15.4286,"faults":[]},
{"points":2,"points_total":20,"average":10.0,"faults":[]},
{"points":7,"points_total":27,"average":9.0,"faults":[]},
{"points":9,"points_total":36,"average":9.0,"faults":[]},
{"points":4,"points_total":40,"average":8.0,"faults":[]},
{"points":4,"points_total":44,"average":7.33333,"faults":[]},
{"points":4,"points_total":48,"average":6.85714,"faults":[]},
{"points":8,"points_total":56,"average":7.0,"faults":[]},
{"points":1,"points_total":57,"average":6.33333,"faults":[]},
{"points":6,"points_total":63,"average":6.3,"faults":[]},
{"points":3,"points_total":66,"average":5.82353,"faults":[]},
{"points":6,"points_total":72,"average":6.0,"faults":[]},
{"points":7,"points_total":79,"average":6.07692,"faults":[]},
{"points":3,"points_total":82,"average":5.85714,"faults":[]},
{"points":0,"points_total":82,"average":5.65517,"faults":[]}
],
"team_name":"Lion Sports"
}
]
So, I need to rebuild/restructure it to get following result.
There will be 20 "Breaks" if no value found in "Breaks" till it reaches to 20 then it should have "null" values.
//the result what i wanted = output expected
[
['Breaks', 'King Sports', 'Lion Sports'],
['1', 12, 18],
['2', 29, 20],
['3', 35, 27],
['4', 43, 36],
['5', 57, 40],
['6', null, 44],
['7', null, 48],
['8', null, 56],
['9', null, 57],
['10', null, 63],
['11', null, 66],
['12', null, 72],
['13', null, 79],
['14', null, 82],
['15', null, null],
['16', null, null],
['17', null, null],
['18', null, null],
['19', null, null],
['20', null, null]
]
You could generate the result array first and the put the values in.
var data = [{ Breaks: [{ points: 12, points_total: 12, average: 8.0, faults: [] }, { points: 17, points_total: 29, average: 11.6, faults: [] }, { points: 6, points_total: 35, average: 11.6667, faults: [] }, { points: 8, points_total: 43, average: 10.75, faults: [] }, { points: 14, points_total: 57, average: 11.4, faults: [] }], team_name: "King Sports" }, { Breaks: [{ points: 18, points_total: 18, average: 15.4286, faults: [] }, { points: 2, points_total: 20, average: 10.0, faults: [] }, { points: 7, points_total: 27, average: 9.0, faults: [] }, { points: 9, points_total: 36, average: 9.0, faults: [] }, { points: 4, points_total: 40, average: 8.0, faults: [] }, { points: 4, points_total: 44, average: 7.33333, faults: [] }, { points: 4, points_total: 48, average: 6.85714, faults: [] }, { points: 8, points_total: 56, average: 7.0, faults: [] }, { points: 1, points_total: 57, average: 6.33333, faults: [] }, { points: 6, points_total: 63, average: 6.3, faults: [] }, { points: 3, points_total: 66, average: 5.82353, faults: [] }, { points: 6, points_total: 72, average: 6.0, faults: [] }, { points: 7, points_total: 79, average: 6.07692, faults: [] }, { points: 3, points_total: 82, average: 5.85714, faults: [] }, { points: 0, points_total: 82, average: 5.65517, faults: [] }], team_name: "Lion Sports" }],
result = data.reduce(function (r, a, i) {
r[0][i + 1] = a.team_name;
a.Breaks.forEach(function (b, j) {
r[j + 1][i + 1] = b.points_total;
});
return r;
}, function (length) {
var a = Array.apply(null, { length: length + 1 }).map(function (_, i) { return [(i || 'Breaks').toString(), null, null] });
return a;
}(20));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

how to match array of ids to object properties that contains their id as part of the property name

I have a object that has had a section_id added to the property names.
"price_min-3155": 54,
"price_min-12863": 23,
"price_min-16152": 43, etc...
I have a array of the section_ids
var sectionIdArray = [3155,12863,16152];
also in the object i have the property subdivision_id which needs to stay as is.
"subdivision_id": 3500,
the end result i am looking is grouping the properties by the section_id and also including the subdivision_id. need to have object array that looks like this.
newArry = [{
subdivision_id: 3500,
section_id: 3155, //"section_id-3155": 3155,
price_min:54, //"price_min-3155": 54,
price_max: 34, // "price_max-3155": 34,
units_occ: 54, //"units_occ-3155": 54,
etc...
},{
subdivision_id: 3500,
section_id: 12863, //"section_id-12863": 12863,
price_min:23, //"price_min-12863": 23,
price_max: 56, // "price_max-12863": 56,
units_occ: 9, //"units_occ-12863": 9,
etc...
}]
javascript,jquery,lodash and linq.js are all good. here is working plunker
working plunker
$scope.model = {
"section_id-3155": 3155,
"price_min-3155": 54,
"units_total-3155": 323,
"price_max-3155": 34,
"units_occ-3155": 54,
"inv_mod-3155": 5,
"inv_fin-3155": 6,
"inv_vdl-3155": 35,
"inv_uc-3155": 45,
}
This should do it:
var data = {
"section_id-3155": 3155,
"price_min-3155": 54,
"units_total-3155": 323,
"price_max-3155": 34,
"units_occ-3155": 54,
"inv_mod-3155": 5,
"inv_fin-3155": 6,
"inv_vdl-3155": 35,
"inv_uc-3155": 45,
"inv_fut-3155": 45,
"inv_con-3155": 45,
"fs_excav-3155": true,
"fs_streets-3155": true,
"fs_stakes-3155": true,
"section_id-12863": 12863,
"subdivision_id": 3500,
"price_min-12863": 23,
"price_max-12863": 56,
"units_occ-12863": 9,
"inv_mod-12863": 32,
"inv_fin-12863": 56,
"inv_vdl-12863": 123,
"inv_uc-12863": 54,
"inv_fut-12863": 76,
"inv_con-12863": 23,
"units_total-12863": 87,
"$$hashKey-12863": "object:60",
"section_id-16152": 16152,
"price_min-16152": 43,
"units_total-16152": 994,
"price_max-16152": 9,
"units_occ-16152": 65,
"inv_mod-16152": 765,
"inv_fin-16152": 34,
"inv_vdl-16152": 65,
"inv_uc-16152": 6,
"inv_fut-16152": 7,
"fs_excav-12863": true,
"fs_paved-12863": true,
"fs_equip-12863": true,
"fs_stakes-12863": true,
"fs_equip-16152": true,
"fs_excav-16152": true,
"fs_paved-16152": true,
"fs_streets-16152": true
};
var sectionIdArray = [3155, 12863, 16152];
var objectArray = sectionIdArray.map(function(id) {
var res = {
subdivision_id: data.subdivision_id
};
Object.keys(data).forEach(function(key) {
var regex = new RegExp("-" + id + "$");
if (regex.test(key)) {
res[key.replace(regex, "")] = data[key];
}
});
return res;
});
//output
document.body.innerHTML = JSON.stringify(objectArray);
Here is what I done using lodash. This works fine with your sample data but can be modified to conform to more strict rules. It is just an example how it can be done with lodash.
$scope.model = {
"section_id-3155": 3155,
"price_min-3155": 54,
"units_total-3155": 323,
"price_max-3155": 34,
"units_occ-3155": 54,
"inv_mod-3155": 5,
"inv_fin-3155": 6,
"inv_vdl-3155": 35,
"inv_uc-3155": 45,
"inv_fut-3155": 45,
"inv_con-3155": 45,
"fs_excav-3155": true,
"fs_streets-3155": true,
"fs_stakes-3155": true,
"section_id-12863": 12863,
"subdivision_id": 3500,
"price_min-12863": 23,
"price_max-12863": 56,
"units_occ-12863": 9,
"inv_mod-12863": 32,
"inv_fin-12863": 56,
"inv_vdl-12863": 123,
"inv_uc-12863": 54,
"inv_fut-12863": 76,
"inv_con-12863": 23,
"units_total-12863": 87,
"$$hashKey-12863": "object:60",
"section_id-16152": 16152,
"price_min-16152": 43,
"units_total-16152": 994,
"price_max-16152": 9,
"units_occ-16152": 65,
"inv_mod-16152": 765,
"inv_fin-16152": 34,
"inv_vdl-16152": 65,
"inv_uc-16152": 6,
"inv_fut-16152": 7,
"fs_excav-12863": true,
"fs_paved-12863": true,
"fs_equip-12863": true,
"fs_stakes-12863": true,
"fs_equip-16152": true,
"fs_excav-16152": true,
"fs_paved-16152": true,
"fs_streets-16152": true
};
$scope.res = {};
var res = _($scope.model)
.pairs()
.groupBy(function (val) {
var parts = val[0].split('-');
return parts[parts.length-1];
})
.transform(function (result, val, key, src) {
if (!isNaN(key)) { // is number
key = +key;
result[key] = _(val)
.zipObject()
.transform(function (result, val, key) {
var parts = key.split('-'), newKey;
parts.splice(-1, 1);
newKey = parts.join('-');
result[newKey] = val;
}, {})
.value();
result[key]['subdivision_id'] = src['subdivision_id'][0][1];
}
}, {})
.value();
$scope.res = res;
I also updated your plunker.
i will give you an idea of a possible abstract algorithm:
iterate over all keys k in $scope.model (for var key in $scope.model) { ...}
in each step iterate over every value v in the sectionIdArray
if v is part of the string k (k.indexOf(v) !== -1) then put it into such a "basket" (eg an array correlated to this sectionId)
for every basket create a new entry for your result-array by evaluating the data there (getting min/max etc) and copying the subvision_id from the original object
if you have any more question about this algorithm don't hesitate to ask, but don't expect me to implement the whole algorithm for you ;)
You can use a temporary object and make then the wanted array.
var data = { "section_id-3155": 3155, "price_min-3155": 54, "units_total-3155": 323, "price_max-3155": 34, "units_occ-3155": 54, "inv_mod-3155": 5, "inv_fin-3155": 6, "inv_vdl-3155": 35, "inv_uc-3155": 45, "inv_fut-3155": 45, "inv_con-3155": 45, "fs_excav-3155": true, "fs_streets-3155": true, "fs_stakes-3155": true, "section_id-12863": 12863, "subdivision_id": 3500, "price_min-12863": 23, "price_max-12863": 56, "units_occ-12863": 9, "inv_mod-12863": 32, "inv_fin-12863": 56, "inv_vdl-12863": 123, "inv_uc-12863": 54, "inv_fut-12863": 76, "inv_con-12863": 23, "units_total-12863": 87, "section_id-16152": 16152, "price_min-16152": 43, "units_total-16152": 994, "price_max-16152": 9, "units_occ-16152": 65, "inv_mod-16152": 765, "inv_fin-16152": 34, "inv_vdl-16152": 65, "inv_uc-16152": 6, "inv_fut-16152": 7, "fs_excav-12863": true, "fs_paved-12863": true, "fs_equip-12863": true, "fs_stakes-12863": true, "fs_equip-16152": true, "fs_excav-16152": true, "fs_paved-16152": true, "fs_streets-16152": true },
keys = Object.keys(data),
result = keys.reduce(function (r, k) {
var p = k.split('-'), o;
if (p[1]) {
if (!(p[1] in r.temp)) {
o = { subdivision_id: data['subdivision_id'] };
r.a.push(o);
r.temp[p[1]] = o;
}
r.temp[p[1]][p[0]] = data[k];
}
return r;
}, { temp: {}, a: [] }).a;
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Convert buffer to array

I am setting memcached with
$memcached->set("item" , ["1" => "hello"]);
anything work in PHP ,
In Node.js with memcached plugin , I get a buffer instead of array in result
<Buffer 61 3a 25 61 34 3a>
I can not convert such buffer to array
In Node.js :
memcached.get("item" , function(err, data) {
console.log(data);
}
Do you have any way ?
arr = [...buffer]
ES6 introduced a lot of other features, besides buffers.
You can even easily append like this:
arr.push(...buffer)
The ... operator expands enumerables such as arrays and buffers when used in array. It also expands them into separate function arguments.
Yes, it's also faster:
... : x100000: 835.850ms
Slice call from prototype : x100000: 2118.513ms
var array,
buffer = new Buffer([1, 4, 4, 5, 6, 7, 5, 3, 5, 67, 7, 4, 3, 5, 76, 234, 24, 235, 24, 4, 234, 234, 234, 325, 32, 6246, 8, 89, 689, 7687, 56, 54, 643, 32, 213, 2134, 235, 346, 45756, 857, 987, 0790, 89, 57, 5, 32, 423, 54, 6, 765, 65, 745, 4, 34, 543, 43, 3, 3, 3, 34, 3, 63, 63, 35, 7, 537, 35, 75, 754, 7, 23, 234, 43, 6, 247, 35, 54, 745, 767, 5, 3, 2, 2, 6, 7, 32, 3, 56, 346, 4, 32, 32, 3, 4, 45, 5, 34, 45, 43, 43]),
iter = 100000;
array = buffer;
console.time("... : x" + iter);
for (var i = iter; i--;) array = [...buffer]
console.timeEnd("... : x" + iter);
console.time("Apply/call/etc : x" + iter);
for (var i = iter; i--;) array = Array.prototype.slice.call(buffer, 0)
console.timeEnd("Apply/call/etc : x" + iter);
There is another way to convert to array of integers
Using toJSON()
Buffer.from('Text of example').toJSON()
{ type: 'Buffer',data: [ 84, 101, 120, 116, 32, 111, 102, 32, 101, 120, 97, 109, 112, 108, 101 ] }
// simple get data
Buffer.from('Text of example').toJSON().data
[ 84, 101, 120, 116, 32, 111, 102, 32, 101, 120, 97, 109, 112, 108, 101 ]
Example of benchmark
// I took this from #user4584267's answer
const buffer = new Buffer([1, 4, 4, 5, 6, 7, 5, 3, 5, 67, 7, 4, 3, 5, 76, 234, 24, 235, 24, 4, 234, 234, 234, 325, 32, 6246, 8, 89, 689, 7687, 56, 54, 643, 32, 213, 2134, 235, 346, 45756, 857, 987, 0790, 89, 57, 5, 32, 423, 54, 6, 765, 65, 745, 4, 34, 543, 43, 3, 3, 3, 34, 3, 63, 63, 35, 7, 537, 35, 75, 754, 7, 23, 234, 43, 6, 247, 35, 54, 745, 767, 5, 3, 2, 2, 6, 7, 32, 3, 56, 346, 4, 32, 32, 3, 4, 45, 5, 34, 45, 43, 43]);
let array = null;
const iterations = 100000;
console.time("...buffer");
for (let i = iterations; i=i-1;) array = [...buffer]
console.timeEnd("...buffer");
console.time("array.prototype.slice.call");
for (let i = iterations; i=i-1;) array = Array.prototype.slice.call(buffer, 0)
console.timeEnd("array.prototype.slice.call");
console.time("toJSON().data");
for (let i = iterations; i=i-1;) array = buffer.toJSON().data
console.timeEnd("toJSON().data");
OUTPUT
...buffer: 559.932ms
array.prototype.slice.call: 1176.535ms
toJSON().data: 30.571ms
or if you want more profesional and custom function in Buffer use this:
Buffer.prototype.toArrayInteger = function(){
if (this.length > 0) {
const data = new Array(this.length);
for (let i = 0; i < this.length; i=i+1)
data[i] = this[i];
return data;
}
return [];
}
Example of benchmark:
const buffer = new Buffer([1, 4, 4, 5, 6, 7, 5, 3, 5, 67, 7, 4, 3, 5, 76, 234, 24, 235, 24, 4, 234, 234, 234, 325, 32, 6246, 8, 89, 689, 7687, 56, 54, 643, 32, 213, 2134, 235, 346, 45756, 857, 987, 0790, 89, 57, 5, 32, 423, 54, 6, 765, 65, 745, 4, 34, 543, 43, 3, 3, 3, 34, 3, 63, 63, 35, 7, 537, 35, 75, 754, 7, 23, 234, 43, 6, 247, 35, 54, 745, 767, 5, 3, 2, 2, 6, 7, 32, 3, 56, 346, 4, 32, 32, 3, 4, 45, 5, 34, 45, 43, 43]);
let array = null;
const iterations = 100000;
console.time("toArrayInteger");
for (let i = iterations; i=i-1;) buffer.toArrayInteger();
console.timeEnd("toArrayInteger");
Ouput:
toArrayInteger: 28.714ms
Note: In the last example I copied a function from Buffer.toJSON and custom it a lite
Here you go:
var buffer = new Buffer([1,2,3])
var arr = Array.prototype.slice.call(buffer, 0)
console.log(arr)
I haven't used memcached so I am not sure just what this buffer represents or what you want to have instead. Sorry. Here is a function to split a buffer up into an array of bytes. More at node.js Buffer docs, hope it helps!
var hex = new Buffer("613a2561343a", "hex");
var l = hex.length; // in bytes
var output = [];
for(var i = 0; i < l; i++){
var char = hex.toString('hex',i,i+1); // i is byte index of hex
output.push(char);
};
console.log(output);
// output: [ '61', '3a', '25', '61', '34', '3a' ]
You can also use Array.from:
memcached.get("item" , function(err, data) {
console.log(Array.from(data));
}
I have a solution, although I am currently trying to find a better one:
function bufToArray(buffer) {
let array = new Array();
for (data of buffer.values()) array.push(data);
return array;
}
EDIT : I found a simpler way:
var buffer = Buffer.from('NodeJS rocks!')
var array = new Function(`return [${Array.prototype.slice.call(buffer, 0)}]`)
But, like someone already said, [...buffer] is faster (and more code efficient).
You can also use new Uint8Array(buffer [, byteOffset [, length]]);
In interent , there was no information about that , but I have found the convert way
In nodejs , I have to use :
var arrayobject = phpjs.unserialize(data.toString());
but , it is very stupid way for getting array , it seem that php serilzie the data when setting memcache .

Categories