-1

I have object like this

{2015:1.5,2016:1.5, 2017:1.5,2018:15 ,2019:1}

I want to create 2d array like this way

[[2015,1.5],[2016,1.5],..]

I tried from this but didn't work. how should I do?

EDIT 1:

basically I have 2 data. one consist of array of year and second consist of array of data. [2015,2016] and data is like [1.5,1]. I want to merge like [[2015,1.5],[2106,1]].

4
  • Your object is wrong. Commented Aug 3, 2017 at 12:33
  • Please provide Your code, current result and desired result. Commented Aug 3, 2017 at 12:34
  • I have got it from backend Commented Aug 3, 2017 at 12:34
  • This is not a valid object. Commas are missing Commented Aug 3, 2017 at 12:36

2 Answers 2

3

If you have a string, you can split it twice:

var s = "2015:1.5 2016:1.5 2017:1.5 2018:15 2019:1";

console.log(
  s.split(" ").map(x => x.split(":"))
);


If you have an object, use Object.entries to convert it to an array:

var obj = {2015:1.5, 2016:1.5, 2017:1.5, 2018:15, 2019:1};

console.log(Object.entries(obj));


var year = [2015, 2016];
var data = [1.5, 1];

console.log(
  year.map((y, i) => [y, data[i]])
);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use Object.keys() and array#map

const obj = {2015:1.5, 2016:1.5, 2017:1.5, 2018:15, 2019:1};

var result = Object.keys(obj).map((key) => [key, obj[key]]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.